假设我们有一个如下所示的示例数据框,
df = pd.DataFrame(np.array([['strawberry', 'red', 3], ['apple', 'red', 6], ['apple', 'red', 5],
['banana', 'yellow', 9], ['pineapple', 'yellow', 5], ['pineapple', 'yellow', 7],
['apple', 'green', 2],['apple', 'green', 6], ['kiwi', 'green', 6]
]),
columns=['Fruit', 'Color', 'Quantity'])
df
Fruit Color Quantity
0 strawberry red 3
1 apple red 6
2 apple red 5
3 banana yellow 9
4 pineapple yellow 5
5 pineapple yellow 7
6 apple green 2
7 apple green 6
8 kiwi green 6
在这个 df 中,我正在逐行检查 Fruit 列中是否有任何变化。
使用 shift() 方法,行偏移 1,使用 fillna() 方法填充 NaN 值,最后使用 ne() 方法完成 True-False 标记。
因此,您可以从索引 1 中检查,草莓变为苹果,它将为“真”。索引2,没有变化,就是“False”。
df['Fruit_Check'] = df.Fruit.shift().fillna(df.Fruit).ne(df.Fruit)
df
Fruit Color Quantity Fruit_Check
0 strawberry red 3 False
1 apple red 6 True
2 apple red 5 False
3 banana yellow 9 True
4 pineapple yellow 5 True
5 pineapple yellow 7 False
6 apple green 2 True
7 apple green 6 False
8 kiwi green 6 True
我的问题是:我还想检查“颜色”列。如果那里有变化, Fruit_Check 列必须是 False 默认值。所以 df 应该是这样的,
df
Fruit Color Quantity Fruit_Check
0 strawberry red 3 False
1 apple red 6 True
2 apple red 5 False
3 banana yellow 9 False
4 pineapple yellow 5 True
5 pineapple yellow 7 False
6 apple green 2 False
7 apple green 6 False
8 kiwi green 6 True
另外我不应该使用 for 循环。因为当我使用我的原始数据时,它需要太多时间。
使用DataFrameGroupBy.shift
为shift
每个组:
df['Fruit_Check'] = df.groupby('Color').Fruit.shift().fillna(df.Fruit).ne(df.Fruit)
print (df)
Fruit Color Quantity Fruit_Check
0 strawberry red 3 False
1 apple red 6 True
2 apple red 5 False
3 banana yellow 9 False
4 pineapple yellow 5 True
5 pineapple yellow 7 False
6 apple green 2 False
7 apple green 6 False
8 kiwi green 6 True
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句