Reputation: 381
What is the cleanest way to do the following transformation in Pandas (Python) :
number color
10 blue
15 red
25 green
35 blue
15 pink
30 green
5 red
20 blue
50 red
into
number color
10 blue
15 FALSE
25 FALSE
35 blue
15 FALSE
30 green
5 FALSE
20 blue
50 red
Essentially, I'd like to change all colors whose number is < 30 but that rule only applies if the color IS NOT blue.
Thanks !
Upvotes: 2
Views: 312
Reputation: 11
Instead of map, you can use "apply". Apply runs the function on each row.
def mod_color(row) :
if row.number < 30 and row.color != 'blue':
row.color = False
return row
df.apply(mod_color, axis=1)
Upvotes: 1
Reputation: 221584
One approach -
df.loc[(df.number < 30) & (df.color != 'blue'),'color'] = False
Sample run -
In [409]: df
Out[409]:
number color
0 10 blue
1 15 red
2 25 green
3 35 blue
4 15 pink
5 30 green
6 5 red
7 20 blue
8 50 red
In [410]: df.loc[(df.number < 30) & (df.color != 'blue'),'color'] = False
In [411]: df
Out[411]:
number color
0 10 blue
1 15 False
2 25 False
3 35 blue
4 15 False
5 30 green
6 5 False
7 20 blue
8 50 red
Upvotes: 2