Vic13
Vic13

Reputation: 561

Changing column values in pandas dataframe

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

Upvotes: 2

Views: 76

Answers (3)

koPytok
koPytok

Reputation: 3733

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)

Upvotes: 3

Pascal Stalder
Pascal Stalder

Reputation: 1

simple oneliner that should work

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

Upvotes: 0

user96564
user96564

Reputation: 1607

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

Upvotes: 1

Related Questions