我有以下内容df,cluster_id date1 2018-01-021 2018-02-011 2018-03-302 2018-04-012 2018-04-232 2018-05-183 2018-06-013 2018-07-303 2018-09-30我喜欢创建一个布尔列recur_pmt,True如果date每个簇 ( df.groupby('cluster_id')) 中的连续值之间的所有差异都为30 < x < 40;和False其他。所以结果就像,cluster_id date recur_pmt1 2018-01-02 False1 2018-02-01 False1 2018-03-30 False2 2018-04-01 True2 2018-04-23 True2 2018-05-18 True3 2018-06-01 False3 2018-07-30 False3 2018-09-30 False我试过了df['recur_pmt'] = df.groupby('cluster_id')['date'].apply( lambda x: (20 < x.diff().dropna().dt.days < 40).all())但它没有用。我也想知道transform在这种情况下它也可以使用。
1 回答

慕丝7291255
TA贡献1859条经验 获得超6个赞
transform
与Series.between
参数一起使用inclusive=False
:
df['recur_pmt'] = df.groupby('cluster_id')['date'].transform(
lambda x: (x.diff().dropna().dt.days.between(20, 40, inclusive=False)).all())
print (df)
cluster_id date recur_pmt
0 1 2018-01-02 False
1 1 2018-02-01 False
2 1 2018-03-30 False
3 2 2018-04-01 True
4 2 2018-04-23 True
5 2 2018-05-18 True
6 3 2018-06-01 False
7 3 2018-07-30 False
8 3 2018-09-30 False
添加回答
举报
0/150
提交
取消