繁体   English   中英

Pandas:对组进行排序并在组内排序

[英]Pandas: Sort groups and sort within group

我的 dataframe df包含具有 EAN、更早和更晚日期、“是”和“否”标签和值的产品。

EAN-Unique  Date         Start  Value 
3324324     2019-04-30   no      0.11
3324324     2018-06-01   yes    56.03
asd2343     2015-03-23   yes     8.02
asd2343     2015-07-11   no      8.45
Xjkhfsd     1999-04-12   yes    12.33
Xjkhfsd     2001-02-01   no      9.11
5234XAR     2013-12-13   no     15.75
5234XAR     2000-12-13   yes     9.00
3434343     1972-05-23   yes     1.26
3434343     1980-11-01   no      2.77

我想对EAN-Uniques 的组进行排序(例如 3324324 是一个组,asd2343 是一个组,依此类推)基于

  • 基于较早日期的最低到最高值和
  • 在每个组内从较早日期到较晚日期。

df应如下所示:

EAN-Unique  Date         Start  Value 
3434343     1972-05-23   yes     1.26
3434343     1980-11-01   no      2.77
asd2343     2015-03-23   yes     8.02
asd2343     2015-07-11   no      8.45
5234XAR     2000-12-13   yes     9.00
5234XAR     2013-12-13   no     15.75
Xjkhfsd     1999-04-12   yes    12.33
Xjkhfsd     2001-02-01   no      9.11
3324324     2018-06-01   yes    56.03
3324324     2019-04-30   no      0.11

我的尝试是对其进行排序

df = df.sort_values(by=['EAN-Unique','Date','Value'], ascending=[True,True,True]).reset_index(drop=True)

但它没有按预期工作。 有人可以帮帮我吗?

谢谢!

创建一个辅助列seq以按起始值存储组顺序

group_order = df.sort_values(['Start', 'Value'], ascending=[False, True])['EAN-Unique'].unique()
seq_map =  dict(zip(group_order, range(len(group_order))))
df['seq'] = df['EAN-Unique'].map(seq_map)
df.sort_values(['seq', 'Date'], inplace=True)
print(df)
  EAN-Unique        Date Start  Value  seq
8    3434343  1972-05-23   yes   1.26    0
9    3434343  1980-11-01    no   2.77    0
2    asd2343  2015-03-23   yes   8.02    1
3    asd2343  2015-07-11    no   8.45    1
7    5234XAR  2000-12-13   yes   9.00    2
6    5234XAR  2013-12-13    no  15.75    2
4    Xjkhfsd  1999-04-12   yes  12.33    3
5    Xjkhfsd  2001-02-01    no   9.11    3
1    3324324  2018-06-01   yes  56.03    4
0    3324324  2019-04-30    no   0.11    4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM