繁体   English   中英

按各组最新的 pandas dataframe 和 select 分组

[英]group by pandas dataframe and select latest in each group

如何将 pandas dataframe 和 select 的值分组为每个组的最新(按日期)?

例如,给定一个按日期排序的 dataframe:

    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

您还可以使用tail with 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

groupby使用idxmaxloc使用slice 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

给定按日期排序的数据框,您可以通过多种方式获得您要求的内容:

像这样:

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)

使用.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

我有类似的问题,最终使用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
#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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM