gpt4 book ai didi

python Pandas : Is There a Faster Way to Split and Recombine a DataFrame based on criteria?

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:50 24 4
gpt4 key购买 nike

我想根据特定列“ContactID”对该 DataFrame 进行分组,但如果该组的列“PaymentType”不包含特定值,那么我想从 DataFrame 中删除整个组。

我有这样的东西:

UniqueID = data.drop_duplicates('ContactID')['ContactID'].tolist()
OnlyRefinance=[]
for i in UniqueID:
splits = data[data['ContactID']==i].reset_index(drop=True)
if any(splits['PaymentType']==160):
OnlyRefinance.append(splits)
OnlyRefinance = pd.concat(OnlyRefinance)

这可行,但速度非常慢,我想知道是否有更快的方法来完成此任务。

最佳答案

您可以使用 groupby.filter 的另一个选项:

data.groupby("ContactID").filter(lambda g: (g.PaymentType == 160).any())

这只会保留 PaymentType 包含 160 的组。

关于 python Pandas : Is There a Faster Way to Split and Recombine a DataFrame based on criteria?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42095584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com