熊猫系列:选择一天中最高价值的指数?

时间:2018-05-14 21:43:22

标签: python pandas

给定一个时间序列,其中每天在不同时间有几个条目,并且每次都有一个值:

import pandas as pd
from datetime import datetime
ts1 = pd.Series([1, 2, 4, 3],
                 index=[datetime(2011,1,2,1,1,1),   # first day
                        datetime(2011,1,2,2,2,2),
                        datetime(2011,1,3,1,1,1),   # second day
                        datetime(2011,1,3,4,4,4)])

如何迭代这个系列,以便为每个日期获得一个索引,该索引对应于该日期的最高值?

对于上面的例子,我希望迭代能够涵盖这些值:

datetime(2011,1,2,2,2,2)   # highest value on 2011-1-2 is 2
datetime(2011,1,3,1,1,1)   # highest value on 2011-1-3 is 4

2 个答案:

答案 0 :(得分:3)

使用频率为“D”的groupby.max对象呼叫pd.Grouper几天。

ts1.groupby(pd.Grouper(freq='D')).max()

2011-01-02    2
2011-01-03    4
Freq: D, dtype: int64

或者,floor分组前的索引 -

ts1.groupby(ts1.index.floor('D')).max()

2011-01-02    2
2011-01-03    4
dtype: int64

或者最后,从索引中查询date -

ts1.groupby(ts1.index.date).max()

2011-01-02    2
2011-01-03    4
dtype: int64

如果您使用Series而不是Index执行此操作,则需要通过.dt访问者调用这些函数。

如果您希望使用索引的最大值,请改用idxmax,然后使用loc索引ts1 -

ts1.loc[ts1.groupby(pd.Grouper(freq='D')).idxmax()]

2011-01-02 02:02:02    2
2011-01-03 01:01:01    4
dtype: int64

答案 1 :(得分:1)

让我们试试(UTF32[])

duplicated