python - 如何根据熊猫中的两列值对一行和前一行进行切片?
问题描述
我已经使用月份列中的值之间的差异来创建差异列。
data_2019['difference'] = data_2019.groupby('propertyId')['month'].diff()
现在我想做以下事情:
对于差异列中有 1 的每一行,只要 propertyId 值与前一行相同,就保留该行和前一行。
解决方案
这是您可以完成此操作的一种方法:
# True for the second row of two consecutive rows
data_2019['difference+'] = data_2019.groupby('propertyId')['month'].diff()==1
# True for the first row of two consecutive rows
data_2019['differenc-'] = data_2019.groupby('propertyId')['month'].diff(periods=-1)==-1
# 'keep' is True if a row is the first or the second or both
data_2019['keep'] = data_2019['difference+'] | data_2019['difference-']
Out:
propertyId month occ difference+ difference- keep
0 a111 3 80.0 False False False
1 a111 5 93.0 False True True
2 a111 6 94.0 True True True
3 a111 7 95.5 True False True
4 a111 10 88.0 False False False
5 b111 2 97.0 False True True
6 b111 3 99.0 True False True
7 c116 2 97.0 False False False
然后你可以将行保留在哪里data_2019['keep']==True
data_2019 = data_2019[data_2019['keep']==True]
推荐阅读
- python - 构建一个函数来滚动 `f` 提供的骰子列表,并计算结果中最大数字为 `x_max` 的概率
- node.js - 在关闭窗口之前调用 REST API (React)
- python - 如何在 Python Scrapy http 请求上设置 cookie?
- javascript - Angular - 冻结第一个选项卡,直到另一个选项卡完全加载
- sql - SQL 条件行号重置
- python - 如何修复“ValueError:没有足够的值来解包(预期 2,得到 1)”
- ios - 是否可以在不使用第三方解决方案的情况下创建在 iOS 应用安装后仍然存在的深层链接?
- python - TensorFlow 中 model.predict 的进展?
- php - 如何使用 Laravel 在 MySQL 中插入表情符号?
- reactjs - 如何在 reactjs 中处理刷新令牌