2

I want to change the value of a Cabin column in my data frame.

Here's my dataframe:

enter image description here

I would like to assign the value to be 1, where the Cabin is not equal to 0. That means the value of C85, C123, E46 should be 1 and rest of the values should be same.

This is the code, but I am getting a value error.

if df_train.Cabin != 0:
   df_train.Cabin = 1
else:
   df_train.Cabin = 0
1
  • Can you post your dataframe not as an image, but as text? Commented Jun 27, 2018 at 17:47

3 Answers 3

3

Just use df.apply:

df_train["new_Cabin"] = df_train["Cabin"].apply(lambda x: x != 0).astype(int)

Also, you can compare column to zero:

df["new_Cabin"] = (df_train["Cabin"] != 0).astype(int)
Sign up to request clarification or add additional context in comments.

3 Comments

All the values are being converted to 1. I dont want to convert 0's to 1.
@Vic13 Maybe, you need to remove quotes " around 0: x != 0 instead of x != "0"
Thanks for the help
1

try np.where

df['newCabin'] = np.where(df['cabin'] != 0, 1, df['cabin'])

print(df)
cabin newCabin
    0        0
  C85        1
    0        0
 C123        1
    0        0
    0        0

and if you dont want extra new column, then you can do this one too

df['cabin'] = np.where(df['cabin'] != 0, 1, df['cabin'])
print(df)
cabin
    0
    1
    0
    1
    0
    0

3 Comments

df['cabin'] = np.where(df['cabin'] != '0', 1, df['cabin']) instead of this f['cabin'] = np.where(df['cabin'] != 0, 1, df['cabin'])
Thanks for the help
I had 0 as a string in my dataframe, thatswhy I used the quote.
0

simple oneliner that should work

df_train['cabin'][df_train['cabin'] != '0'] = 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.