idt*_*_tt 3 python pandas pandas-groupby
我有一个看起来像这样的数据框:
pd.DataFrame({'a': ['cust1', 'cust1', 'cust1', 'cust2', 'cust2', 'cust3', 'cust3', 'cust3', 'cust4', 'cust4'],
'year': [2017, 2018, 2019, 2018, 2019, 2017, 2018, 2019, 2018, 2019],
'cond': [True, True, False, True, True, True, True, True, True, True],
'startDate': [2017, 2017, 2017, 2018, 2018, 2017, 2017, 2017, 2017, 2017]})
endYear = 2019
a year cond startDate
0 cust1 2017 True 2017
1 cust1 2018 True 2017
2 cust1 2019 False 2017
3 cust2 2018 True 2018
4 cust2 2019 True 2018
5 cust3 2017 True 2017
6 cust3 2018 True 2017
7 cust3 2019 True 2017
8 cust4 2018 True 2017
9 cust4 2019 True 2017
Run Code Online (Sandbox Code Playgroud)
对于“a”列中的每个组,我需要检查“cond”列在“startDate”列(每个组可以不同)和“endYear”之间的所有年份是否具有“True”值。
我生成的数据框应如下所示:
a final_score
0 cust1 False
1 cust2 True
2 cust3 True
3 cust4 False
Run Code Online (Sandbox Code Playgroud)
逻辑:
cust1 = False 作为 2019 年值 = False
cust2 = True 作为 startDate 2018 并且对于 2018 和 2019 之间的所有年份 'cond' 为 True
cust3 = True 作为 startDate 2017 并且对于 2017 和 2019 之间的所有年份 'cond' 为 True
cust4 = False 作为 startDate 2017 但没有 2017 年的数据所以条件不满足
IIUC,您可以使用reindex按组填充空白年份然后检查True:
print (df.groupby("a").apply(lambda d: d.set_index("year").reindex(range(d["startDate"].min(), endYear+1))["cond"].eq(True).all()))
a
cust1 False
cust2 True
cust3 True
cust4 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)