首页 > 解决方案 > 按分数比较数据框列中的值

问题描述

我有一个数据集:

在此处输入图像描述

我需要将上个月的索引(在一组 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:转换无法产生聚合结果

没有“应用”,代码就可以工作。我究竟做错了什么?

所需的输出是这样的: 在此处输入图像描述

感谢您的任何建议

标签: pythonpandas

解决方案


您可以尝试从上限groupby.shift减去1:indexclip

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

推荐阅读