在将groupby应用于python数据帧时,如何获取组的第一个时间戳(索引)?
我的数据原则上如下所示:在将groupby应用于python数据帧时,如何获取组的第一个时间戳(索引)?,python,group-by,pandas,timestamp,Python,Group By,Pandas,Timestamp,我的数据原则上如下所示: 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:0
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
我想将它分组到“一”列上,并获取每个组的第一个时间戳。
将此应用于列'two'效果很好,但对时间戳不起作用
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