在pandas框架中选择每个组中的最新内容

o2g1uqev  于 2023-11-15  发布在  其他
关注(0)|答案(6)|浏览(151)

如何对pandas的值进行分组并从每组中选择最新的值(按日期)?
例如,给定一个按日期排序的数组:

id     product   date
0   220    6647     2014-09-01 
1   220    6647     2014-09-03 
2   220    6647     2014-10-16
3   826    3380     2014-11-11
4   826    3380     2014-12-09
5   826    3380     2015-05-19
6   901    4555     2014-09-01
7   901    4555     2014-10-05
8   901    4555     2014-11-01

字符串
按id或产品分组,并选择最新的产品:

id     product   date
2   220    6647     2014-10-16
5   826    3380     2015-05-19
8   901    4555     2014-11-01

polhcujo

polhcujo1#

您也可以使用tail和groupby来获取组的最后n个值:

df.sort_values('date').groupby('id').tail(1)

    id  product date
2   220 6647    2014-10-16
8   901 4555    2014-11-01
5   826 3380    2015-05-19

字符串

wyyhbhjk

wyyhbhjk2#

groupby中使用idxmax,用loc切片df

df.loc[df.groupby('id').date.idxmax()]

    id  product       date
2  220     6647 2014-10-16
5  826     3380 2015-05-19
8  901     4555 2014-11-01

字符串

to94eoyn

to94eoyn3#

我遇到了类似的问题,最终使用了drop_duplicates而不是groupby
与上面建议的其他方法相比,它在大型数据集上的运行速度明显更快。

df.sort_values(by="date").drop_duplicates(subset=["id"], keep="last")

    id  product        date
2  220     6647  2014-10-16
8  901     4555  2014-11-01
5  826     3380  2015-05-19

字符串

ej83mcc0

ej83mcc04#

给定一个按日期排序的数组,您可以通过多种方式获得您所要求的内容:
就像这样:

df.groupby(['id','product']).last()

字符串
就像这样:

df.groupby(['id','product']).nth(-1)


或者像这样:

df.groupby(['id','product']).max()


如果不希望idproduct显示为索引,请使用groupby(['id', 'product'], as_index=False)。或者用途:

df.groupby(['id','product']).tail(1)

2mbi3lxu

2mbi3lxu5#

要使用.tail()作为聚合方法并保持分组不变,请执行以下操作:

df.sort_values('date').groupby('id').apply(lambda x: x.tail(1))

        id  product date
id              
220 2   220 6647    2014-10-16
826 5   826 3380    2015-05-19
901 8   901 4555    2014-11-01

字符串

hpcdzsge

hpcdzsge6#

#import datetime library
from datetime import datetime as dt

#transform the date column to ordinal, or create a temp column converting to ordinal.
df['date'] = df.date.apply(lambda date: date.toordinal())

#apply aggregation function depending your desire. Earliest or Latest date.
latest_date = df.groupby('id').agg(latest=('date', max)) 
earliest_date = df.groupby('id').agg(earliest=('date', min)) 

#convert it from ordinal back to date.
df['date'] = df.date.apply(lambda date: dt.fromordinal(date))

#This operation may take seconds on millions of records.

字符串

相关问题