[英]Conditional transform of a Series subset in Pandas
在Pandas(Python)中進行以下轉換的最干凈方法是什么:
number color
10 blue
15 red
25 green
35 blue
15 pink
30 green
5 red
20 blue
50 red
成
number color
10 blue
15 FALSE
25 FALSE
35 blue
15 FALSE
30 green
5 FALSE
20 blue
50 red
本質上,我想更改數字小於30的所有顏色,但是該規則僅在顏色不是藍色的情況下適用。
謝謝 !
一種方法-
df.loc[(df.number < 30) & (df.color != 'blue'),'color'] = False
樣品運行-
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
可以使用“應用”代替地圖。 Apply在每一行上運行該函數。
def mod_color(row) :
if row.number < 30 and row.color != 'blue':
row.color = False
return row
df.apply(mod_color, axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.