Reputation: 561
I want to change the value of a Cabin
column in my data frame.
Here's my dataframe:
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
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
Reputation: 1
simple oneliner that should work
df_train['cabin'][df_train['cabin'] != '0'] = 1
Upvotes: 0
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