我有一个数据框,其中一列中有各种值。我想确保在dataframe中每个惟一的列元素都有3个最新的条目。
我有:

      Group      Date        Value
        A        10/1/2017    4.4
        A        8/3/2017     9.2
        A        5/3/2017     8.4
        A        4/4/2017     4.4
        B        12/1/2015    4.4
        B        8/3/2015     9.2
        B        5/4/2015     8.4
        B        4/5/2015     4.4

我想要:
      Group      Date        Value
        A        10/1/2017    4.4
        A        8/3/2017     9.2
        A        5/3/2017     8.4
        B        12/1/2015    4.4
        B        8/3/2015     9.2
        B        5/4/2015     8.4

日期是日期时间。我不知道如何在这篇文章中代表其他人。
我可以用下面的代码得到这个:
new_df = pd.DataFrame()
for group in df['Group'].unique():

    temp_df = df[df['Group'] == group]
    temp_df = temp_df[0:3]

    if new_df.empty:

       new_df = temp_df

    else:

       new_df.append(temp_df)

有没有更像蟒蛇一样的方法?
提前谢谢。

最佳答案

下面呢:

df.sort_values(by='Date', ascending=False).groupby('Group').head(3)

在我的小测试数据集上,这将返回以下信息(我使用head(2)):
    Group   Date
1   c   2050-01-01
8   a   2032-02-03
0   a   2030-01-01
9   c   2029-01-01
10  b   2018-01-01
2   b   2017-02-03

如您所见,不同组的值不再很好地组合在一起。我们可以先在“Group”上排序,然后在“Date”上排序:
df.sort_values(by=['Group', 'Date'], ascending=[True,False]).groupby('Group').head(3)


    Group   Date
8   a   2032-02-03
0   a   2030-01-01
10  b   2018-01-01
2   b   2017-02-03
1   c   2050-01-01
9   c   2029-01-01

关于python - Pandas 数据框的复杂子集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52883238/

10-14 18:05
查看更多