python - 按分数比较数据框列中的值
问题描述
我有一个数据集:
我需要将上个月的索引(在一组 id 中)与前两个月的索引进行比较,并检查它是否相同。
我正在尝试代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id':[1,1,1,1,2,2,2,2,3,3,3,3],
'month':[202001,202002,202003,202004,202001,202002,202003,202004,202001,202002,202003,202004,],
'index':[3, 3, 3, 3, 4, 4, 5, 5, 2, 3, 3, 3]})
df['check']=np.where(df.sort_values(['id', 'month'])
.groupby('id')['index']
.apply(lambda x: x.shift(3))
.transform('nunique')>1,1,0)
它返回错误:ValueError:转换无法产生聚合结果
没有“应用”,代码就可以工作。我究竟做错了什么?
感谢您的任何建议
解决方案
您可以尝试从上限groupby.shift
减去1:index
clip
df['check'] = df['index'].sub(df.groupby("id")['index'].shift(2)).clip(upper=1)
print(df)
id month index check
0 1 202001 3 NaN
1 1 202002 3 NaN
2 1 202003 3 0.0
3 1 202004 3 0.0
4 2 202001 4 NaN
5 2 202002 4 NaN
6 2 202003 5 1.0
7 2 202004 5 1.0
8 3 202001 2 NaN
9 3 202002 3 NaN
10 3 202003 3 1.0
11 3 202004 3 0.0
推荐阅读
- flutter - 是否可以使用两个不同的 Firebase 查询并组合 Docsnapshot 结果?
- azure - 导出 ARM 模板时出错
- python - Python 数学绘图库
- java - 无法找到或加载主类 com.amazonaws.services.lambda.runtime.api.client.AWSLambda
- datasource - 如何更新 Apache Druid 中的现有数据
- prisma - 阵列中的棱镜拼接项目
- json - VS Code 中的 WSL 集成 - 如何在 Setting.json 中设置它而不发出警告
- server - Zenko云服务器的配置
- python - 为什么 contextlib.redirect_stderr 上下文管理器没有捕获异常输出?
- typescript - 获取传入 props 的组件的 props 类型