Skip to main content
 首页 » 编程设计

python之将 groupby 应用于 python pandas 数据帧时,如何获取组的第一个时间戳(索引)

2024年11月01日11lvdongjie

原则上我的数据是这样的:

                            one  two 
timestamp                            
2013-12-06 00:00:01.200000    1    1 
2013-12-06 00:00:02.200000    1    2 
2013-12-06 00:00:03.200000    2    1 
2013-12-06 00:00:04.200000    3    5 
2013-12-06 00:00:05.200000    1    2 

我想将它分组在“一”列上,并获取每组的第一个时间戳。 将其应用于“二”列效果很好,但不适用于时间戳。

df_2 = df['two'].groupby(df['one']).first() 

给出:

one 
1      1 
2      1 
3      5 

但是当我将相同的东西应用到索引时,它告诉我没有属性 'first'。

df_3 = df.index.groupby(df['one']).first() 

有谁知道如何做到这一点?

请您参考如下方法:

你可以使用groupby/apply:

>>> grouped = df.groupby('one') 
>>> grouped.apply(lambda x: x.index[0]) 
one 
1     2013-12-06 00:00:01.200000 
2     2013-12-06 00:00:03.200000 
3     2013-12-06 00:00:04.200000 
dtype: datetime64[ns] 

顺便说一下,

df_2 = df['two'].groupby(df['one']).first() 

也可以表示为

>>> grouped['two'].first() 
one 
1      1 
2      1 
3      5 
Name: two, dtype: int64