python - 熊猫将行与条件进行比较
问题描述
假设我们有一个如下所示的示例数据框,
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() 方法完成真假标签。
所以你可以从索引 1 中检查,草莓变成苹果,它将是“真”。索引 2,没有变化,它将是“假”。
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
推荐阅读
- python - 为什么使用带有 pybind11 的犰狳矩阵会导致堆损坏?
- ios - 选择器 'didReceiveNotificationResponse:' IOS 通知没有已知的类方法
- javascript - 努力将数组的索引作为道具传递给另一个组件
- python - 丢弃方差为零的组
- c# - 搜索列表中是否存在字符串
- wordpress - WordPress 网站重定向到未知链接(由于插件/恶意软件 Zend Fonts WP)
- react-native - 反应原生底部选项卡导航到所需屏幕
- jquery - 我希望它根据一天横向滚动
- flutter - Flutter中可滚动的Carousel + GridView + GridView + GridView
- templates - 为 Rstudio (default.R) 创建一个模板脚本,其中创建日期自动插入到脚本中