gpt4 book ai didi

python - Pandas 在 groupby 之后获得行

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:20 25 4
gpt4 key购买 nike

假设我有以下数据集:

uid iid val
1 1 2
1 2 3
1 3 4
1 4 4.5
1 5 5.5
2 1 3
2 2 3
2 3 4
3 4 4.5
3 5 5.5

根据这些数据,我想先按 uid 分组,然后从每个 uid 中获取最后 20% 的行数。

即,由于 uid=1 有 5 行,我想从 uid=1 中获取最后 1 行(5 的 20%)。

下面是我想做的:

df.groupby('uid').tail([20% of each uid])

谁能帮帮我?

最佳答案

您可以尝试将自定义函数应用于 groupby 对象。在函数内部计算应获取多少行,并使用该行数获取组的 tailint 向 0 舍入,因此任何少于 5 行的组都不会为结果贡献任何行。

df.groupby('uid').apply(lambda x: x.tail(int(0.2*x.shape[0])))

关于python - Pandas 在 groupby 之后获得行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448895/

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