Reputation: 3441
I have a pandas dataframe df
with three columns A, B, and C
. I would like to create a new column D
in df
based on the value of column C
. If the value of a pandas record in column C
is in values
list, I want the value of corresponding cell in column D
set to 1, otherwise 0.
# df: given dataframe
# values: given list
df["D"] = None #Creating a new column
df.loc[~df[df["C"].isin(values)].index]["D"] = 1
df.loc[df[df["C"].isin(values)].index]["D"] = 0
But, when I check the column D
, the value assignment did not occur and all its cells are equal to None. I'm wondering if anybody can advice me how to fix this problem.
Upvotes: 0
Views: 37
Reputation: 3739
use .loc
to fill column D
df['D']=1
df.loc[df["C"].isin(values),"D"]=0
Upvotes: 1