Add new column in Pandas DataFrame Python [duplicate]
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55