如何选择熊猫中每个唯一记录的最后 5 行

Ale*_*nel 5 dataframe python-3.x pandas

使用 python 3,我正在尝试为“名称”列中的每个唯一行获取“编号”列中的最后 5 条记录。这在python中究竟如何完成?我的 df 看起来像这样:

Name    Number
a   5
a   6
b   7
b   8
a   9
a   10
b   11
b   12
a   9
b   8
Run Code Online (Sandbox Code Playgroud)

我在 SQL 中看到了相同的例子(像这样一个Get sum of last 5 rows for each unique id),但这很耗时,我想学习如何在 python 中做到这一点。

我的预期输出 df 将是这样的:

Name    1   2   3   4   5
a   5   6   9   10  9
b   7   8   11  12  8
Run Code Online (Sandbox Code Playgroud)

Sco*_*ton 2

我认为你需要这样的东西:

df_out = df.groupby('Name').tail(5)
df_out.set_index(['Name', df_out.groupby('Name').cumcount() +1])['Number'].unstack()
Run Code Online (Sandbox Code Playgroud)

输出:

      1  2   3   4  5
Name                 
a     5  6   9  10  9
b     7  8  11  12  8
Run Code Online (Sandbox Code Playgroud)