gpt4 book ai didi

python - 按最后日期的唯一名称和状态分组

转载 作者:太空狗 更新时间:2023-10-30 01:18:02 28 4
gpt4 key购买 nike

我想分析每辆维修过的汽车和新车的统计数据。数据样本为:

Name   IsItNew    ControlDate
Car1 True 31/01/2018
Car2 True 28/02/2018
Car1 False 15/03/2018
Car2 True 16/04/2018
Car3 True 30/04/2018
Car2 False 25/05/2018
Car1 False 30/05/2018

所以,我应该按名称 groupby,如果 IsItNew 列中有 False,我应该设置 False 和第一个日期,当 False 发生时。

我用 nunique() 尝试了 groupby:

df = df.groupby(['Name','IsItNew', 'ControlDate' ])['Name'].nunique()

但是,它会返回每个组中唯一项的计数。

我怎样才能只收到分组的唯一项目而没有任何计数?

Actual result is:

Name IsItNew ControlDate
Car1 True 31/01/2018 1
False 15/03/2018 1
30/05/2018 1
Car2 True 28/02/2018 1
16/04/2018 1
False 25/05/2018 1
Car3 True 30/04/2018 1


Expected Result is:

Name IsItNew ControlDate
Car1 False 15/03/2018
Car2 False 25/05/2018
Car3 True 30/04/2018

如果有任何想法,我将不胜感激。谢谢)

最佳答案

一种方法是GroupBy Name,并使用两个函数在IsItNew 上聚合。自定义一个使用 any 检查是否有任何 False 值,和 idxmin , 找到第一个 False 的索引,稍后您可以使用它来索引 ControlDate 上的数据帧:

df_ = df.groupby('Name').agg({'IsItNew':
{'IsItNew':lambda x: ~(~x).any(),
'ControlDate':'idxmin'}})
.droplevel(0, axis=1)
.reset_index()

df_['ControlDate'] = df.loc[df_['ControlDate'].values, 'ControlDate'].reset_index(drop=True)

xName IsItNew ControlDate
0 Car1 False 15/03/2018
1 Car2 False 25/05/2018
2 Car3 True 30/04/2018

关于python - 按最后日期的唯一名称和状态分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394262/

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