Python 如何使用fill_值对熊猫中的时间序列重新采样?
我有一个Python 如何使用fill_值对熊猫中的时间序列重新采样?,python,pandas,time-series,resampling,Python,Pandas,Time Series,Resampling,我有一个TimeSeries整数,我想使用resample()对其进行下采样。问题是我有一些缺少数据的时段被转换为NaN。由于pandas不支持整数,因此将整数转换为浮点数 >>> dates = (datetime(2013, 1, 1), datetime(2013,1,2), datetime(2013,3,1)) >>> s = Series([1,2,4],index=dates) >>> s 2013-01-01 1 201
TimeSeries
整数,我想使用resample()
对其进行下采样。问题是我有一些缺少数据的时段被转换为NaN
。由于pandas不支持整数,因此将整数转换为浮点数
>>> dates = (datetime(2013, 1, 1), datetime(2013,1,2), datetime(2013,3,1))
>>> s = Series([1,2,4],index=dates)
>>> s
2013-01-01 1
2013-01-02 2
2013-03-01 4
dtype: int64
>>> s.resample('M', how='sum')
2013-01-31 3
2013-02-28 NaN
2013-03-31 4
Freq: M, dtype: float64
# Desired output (doesn't work)
>>> s.resample('M', how='sum', fill_value=0)
2013-01-31 3
2013-02-28 0
2013-03-31 4
Freq: M, dtype: int64
是否可以像使用reindex(fill\u value=0)
一样,使用fill\u值对缺失数据重新采样TimeSeries
?我不希望我的整数被转换成浮点数
>>> dates = (datetime(2013, 1, 1), datetime(2013,1,2), datetime(2013,3,1))
>>> s = Series([1,2,4],index=dates)
>>> s
2013-01-01 1
2013-01-02 2
2013-03-01 4
dtype: int64
>>> s.resample('M', how='sum')
2013-01-31 3
2013-02-28 NaN
2013-03-31 4
Freq: M, dtype: float64
# Desired output (doesn't work)
>>> s.resample('M', how='sum', fill_value=0)
2013-01-31 3
2013-02-28 0
2013-03-31 4
Freq: M, dtype: int64
您可以定义自己的函数以避免NaN
In [36]: def _sum(x):
....: if len(x) == 0: return 0
....: else: return sum(x)
....:
In [37]: s.resample('M', how=_sum)
Out[37]:
2013-01-31 3
2013-02-28 0
2013-03-31 3
Freq: M, dtype: int64
真奇怪,你的第三个值是4(索引为2013-03-01)。@waitingkuo你说得对。修复了复制和粘贴错误。当然,但这只是将int转换为float,然后再转换回int。我不想通过将int转换为float而失去任何精度。我认为在将int转换为float时没有精度问题。在您关心转换问题的同时,我添加了另一种方法,希望它能有所帮助。我不认为这是真的:int(float(max_int))==max_int
其中max_int=np.iinfo(np.int64)。max
返回False
使用pandas 0.18.0,现在有了一种更简单、更快的方法:s.resample('M').sum().fillna(0)