I need to set the value of one column based on the value of another in a Pandas dataframe. This is the logic:
if df[\'c1\'] == \'Value\':
df[\'c2\'] = 10
Note the tilda that reverses the selection. It uses pandas methods (i.e. is faster than if
/else
).
df.loc[(df['c1'] == 'Value'), 'c2'] = 10
df.loc[~(df['c1'] == 'Value'), 'c2'] = df['c3']
You can use np.where() to set values based on a specified condition:
#df
c1 c2 c3
0 4 2 1
1 8 7 9
2 1 5 8
3 3 3 5
4 3 6 8
Now change values (or set) in column ['c2']
based on your condition.
df['c2'] = np.where(df.c1 == 8,'X', df.c3)
c1 c3 c4
0 4 1 1
1 8 9 X
2 1 8 8
3 3 5 5
4 3 8 8