gpt4 book ai didi

python - Pandas idxmax() 不适用于按包含 NaN 的时间段分组的系列

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:03 25 4
gpt4 key购买 nike

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

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. 每年最高限额的日期对于那些没有数据的年份,应该有一个nan。

要解决 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尚未修复,建议的分类数据解决方法似乎不适用于时间分组/重采样数据。

谁能为这种情况提供合适的解决方法,或者针对上述问题提供完全不同(且有效)的解决方法?

提前致谢!

最佳答案

问题是您没有 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]

关于python - Pandas idxmax() 不适用于按包含 NaN 的时间段分组的系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53081877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com