熊猫idxmax()不适用于按包含NaN的时间段分组的系列

时间:2018-10-31 11:03:53

标签: python pandas

我有一个“系列”,其中包含几年中按天计的标量值索引。几年来没有数据。

2014-10-07    5036.883410
2013-10-11    5007.515654
2013-10-27    5020.184053
2014-09-12    5082.379630
2014-10-14    5032.669801
2014-10-30    5033.276159
2016-10-03    5046.921912
2016-10-19    5141.861889
2017-10-06    5266.138810

我想从中得到 1.每年最高 2.每年最高的日期 对于那些没有数据的年份,应该有一个数字。

要解决1.以下工作:

import pandas as pd
import numpy as np

data= pd.Series( index=pd.DatetimeIndex(['2014-10-07', '2013-10-11', '2013-10-27', '2014-09-12', '2014-10-14', '2014-10-30', '2016-10-03', '2016-10-19', '2017-10-06'], dtype='datetime64[ns]', name='time', freq=None), data=np.array([5036.88341035, 5007.51565355, 5020.18405295, 5082.37963023, 5032.66980146, 5033.27615931, 5046.92191246, 5141.86188915, 5266.1388102 ]))

# get maximum of each year  
data.resample('A').max()

但是,我尝试使用其他选项来获取具有最大值的日期索引,但是它们都失败了:

data.resample('A').idxmax()

这会引发以下属性错误:

AttributeError: 'DatetimeIndexResampler' object has no attribute 'idxmax'

然后我尝试了以下操作:

data.groupby(pd.TimeGrouper('A')).idxmax()

但是这给出了没有指定的ValueError。 然后,我发现this的解决方法:

data.groupby(pd.TimeGrouper('A')).agg( lambda x : x.idxmax() )

但我也没穿临时分组数据:

ValueError: attempt to get argmax of an empty sequence

显然,报告的bug尚未得到修复,分类数据的建议解决方法似乎不适用于时间分组/重采样的数据。

任何人都可以针对这种情况提供合适的解决方法,或者为上述问题提供完全不同(高效)的解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

问题是您在2015年没有记录,但是由于它在您的年份范围内,所以创建了2015年的时间段。您需要手动处理这种情况:

data.resample('A').agg(
    lambda x : np.nan if x.count() == 0 else x.idxmax()
)

输出:

time
2013-12-31   2013-10-27
2014-12-31   2014-09-12
2015-12-31          NaT
2016-12-31   2016-10-19
2017-12-31   2017-10-06
Freq: A-DEC, dtype: datetime64[ns]