gpt4 book ai didi

python - 使用多个条件对 Pandas 进行排序和重组

转载 作者:行者123 更新时间:2023-12-04 08:48:34 27 4
gpt4 key购买 nike

这是样本数据 -

Product     Type        Name    Time        Value
Product a Medicare CVS 2018-10-05 10
Product a Medicare Cigna 2018-10-05 20
Product a Medicare United 2018-10-05 30
Product a Medicare Humana 2018-10-05 40
Product a Medicare Centene 2018-10-05 50
Product a Comm CVS 2018-10-05 20
Product a Comm Cigna 2018-10-05 30
Product a Comm United 2018-10-05 40
Product a Comm Humana 2018-10-05 50
Product a Comm Centene 2018-10-05 60
Product a Medicare CVS 2019-10-03 30
Product a Medicare Cigna 2019-10-03 20
Product a Medicare United 2019-10-03 10
Product a Medicare Humana 2019-10-03 5
Product a Medicare Centene 2019-10-03 12
Product a Comm CVS 2019-10-03 87
Product a Comm Cigna 2019-10-03 43
Product a Comm United 2019-10-03 50
Product a Comm Humana 2019-10-03 30
Product a Comm Centene 2019-10-03 90
首先,我需要在“时间”中找到最新的一周。
在上表中是 2019-10-03。
现在在那一周,我需要按每个“类型”的值对前 2 个“名称”进行排序/查找。
然后,我需要创建一个如下所示的数据框 -
2019 年 10 月 3 日当周“Medicare”的前 2 名“名称”是 CVS 和 Cigna。
2019 年 10 月 3 日当周“Comm”的前 2 名“名称”是 Centene 和 CVS。
Product    Type         Name    Time       Value
Product a Medicare CVS 2018-10-05 10
Product a Medicare Cigna 2018-10-05 20
Product a Comm Centene 2018-10-05 60
Product a Comm CVS 2018-10-05 20
Product a Medicare CVS 2019-10-03 30
Product a Medicare Cigna 2019-10-03 20
Product a Comm Centene 2019-10-03 90
Product a Comm CVS 2019-10-03 87


最佳答案

第一个过滤器Product , TypeName组合最新的日期时间,然后使用 merge对于所有日期时间的过滤器组合:

df['Time'] = pd.to_datetime(df['Time'])

df1= (df[df['Time'].eq(df['Time'].max())]
.sort_values('Value', ascending=False)\
.groupby(['Product', 'Type'])\
.head(2))
print (df1)
Product Type Name Time Value
19 Product a Comm Centene 2019-10-03 90
15 Product a Comm CVS 2019-10-03 87
10 Product a Medicare CVS 2019-10-03 30
11 Product a Medicare Cigna 2019-10-03 20

df = (df.merge(df1[['Product','Type', 'Name']])
.sort_values(['Product','Time','Type','Value'],
ascending=[True, True,True, False]))
print (df)
Product Type Name Time Value
6 Product a Comm Centene 2018-10-05 60
4 Product a Comm CVS 2018-10-05 20
2 Product a Medicare Cigna 2018-10-05 20
0 Product a Medicare CVS 2018-10-05 10
7 Product a Comm Centene 2019-10-03 90
5 Product a Comm CVS 2019-10-03 87
1 Product a Medicare CVS 2019-10-03 30
3 Product a Medicare Cigna 2019-10-03 20

关于python - 使用多个条件对 Pandas 进行排序和重组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64185752/

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