gpt4 book ai didi

python - Pandas - 排序并进入 groupby

转载 作者:太空狗 更新时间:2023-10-30 00:59:27 24 4
gpt4 key购买 nike

我有以下数据框:

                       uniq_id    value
2016-12-26 11:03:10 001 342
2016-12-26 11:03:13 004 5
2016-12-26 12:03:13 005 14
2016-12-26 12:03:13 008 114
2016-12-27 11:03:10 009 343
2016-12-27 11:03:13 013 5
2016-12-27 12:03:13 016 124
2016-12-27 12:03:13 018 114

而且我需要获取每天按值排序的前 N ​​条记录。像这样(对于 N=2):

2016-12-26   001   342
008 114
2016-12-27 009 343
016 124

请建议在 pandas 0.19.x 中执行此操作的正确方法

最佳答案

不幸的是,还没有像 DataFrameGroupBy.nlargest() 这样的方法,它允许我们执行以下操作:

df.groupby(...).nlargest(2, columns=['value'])

所以这里有一个有点难看但可行的解决方案:

In [73]: df.set_index(df.index.normalize()).reset_index().sort_values(['index','value'], ascending=[1,0]).groupby('index').head(2)
Out[73]:
index uniq_id value
0 2016-12-26 1 342
3 2016-12-26 8 114
4 2016-12-27 9 343
6 2016-12-27 16 124

PS 我认为一定有更好的......

更新:如果您的 DF 没有重复的索引值,则以下解决方案也应该有效:

In [117]: df
Out[117]:
uniq_id value
2016-12-26 11:03:10 1 342
2016-12-26 11:03:13 4 5
2016-12-26 12:03:13 5 14
2016-12-26 12:33:13 8 114 # <-- i've intentionally changed this index value
2016-12-27 11:03:10 9 343
2016-12-27 11:03:13 13 5
2016-12-27 12:03:13 16 124
2016-12-27 12:33:13 18 114 # <-- i've intentionally changed this index value

In [118]: df.groupby(pd.TimeGrouper('D')).apply(lambda x: x.nlargest(2, 'value')).reset_index(level=1, drop=1)
Out[118]:
uniq_id value
2016-12-26 1 342
2016-12-26 8 114
2016-12-27 9 343
2016-12-27 16 124

关于python - Pandas - 排序并进入 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41330749/

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