Skip to main content
 首页 » 编程设计

python之尝试将函数应用于 Pandas 时间序列重采样时出错

2025年05月04日17softidea

我正在尝试获取时间序列的第一个元素,但是当我尝试使用 apply 获取它时似乎出现了一些问题。例如:

a = pd.Series(['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04', '2014-01-09']) 
a = pd.to_datetime(a).reset_index().set_index(0) 
a 
 
            index 
0    
2014-01-01  0 
2014-01-02  1 
2014-01-03  2 
2014-01-04  3 
2014-01-09  4 

当我执行 a.resample('2D').apply(lambda x: x[0]) 时,我得到了 IndexError: index out of bounds。我怀疑这是因为我试图调用空系列的 0 元素,但似乎并非如此,而是使用 .apply 重新采样时出现问题。我这样说是因为这个结果:

a.resample('2D').apply(lambda x: min(x)) 
 
            index 
0    
2014-01-01  index 
2014-01-03  index 
2014-01-05  index 
2014-01-07  index 
2014-01-09  index 

郑重声明,a.resample('2D').apply(lambda x: x.min()) 运行良好。知道如何获取每两天的第一项并在没有时返回 NaN 吗?

请您参考如下方法:

这就是你想要的吗?

a.resample('2D').first() 
Out[251]:  
            index 
0                 
2014-01-01    0.0 
2014-01-03    2.0 
2014-01-05    NaN 
2014-01-07    NaN 
2014-01-09    4.0 

x[0] 不起作用的原因是日期范围内存在间隙,该组中将有 0 行。您可以通过以下方式检查它:

a.resample('2D').apply(lambda x: len(x)) 
Out[257]:  
            index 
0                 
2014-01-01      2 
2014-01-03      2 
2014-01-05      0 
2014-01-07      0 
2014-01-09      1 

解决这个问题的方法是添加一个检查:

a.resample('2D').apply(lambda x: x[0] if len(x)>0 else np.nan) 
Out[258]:  
            index 
0                 
2014-01-01    0.0 
2014-01-03    2.0 
2014-01-05    NaN 
2014-01-07    NaN 
2014-01-09    4.0