首页 > 解决方案 > 采样数据帧考虑 NaN 值+熊猫

问题描述

我有一个如下所示的数据框。我想用“3S”进行采样所以有些情况下存在 NaN。我所期望的是数据框应该使用“3S”进行采样,并且如果在两者之间发现任何“NaN”,则停在那里并从该索引开始采样。我尝试使用dataframe.apply 方法来实现,但它看起来很复杂。有什么捷径可以实现吗?

df.sample(n=3)

生成输入的代码:

index = pd.date_range('1/1/2000', periods=13, freq='T')
series = pd.DataFrame(range(13), index=index)
print series

series.iloc[4] = 'NaN'
series.iloc[10] = 'NaN'

我尝试进行采样,但之后不知道如何进行。

2015-01-01 00:00:00    0.0
2015-01-01 01:00:00    1.0
2015-01-01 02:00:00    2.0
2015-01-01 03:00:00    2.0
2015-01-01 04:00:00    NaN
2015-01-01 05:00:00    3.0
2015-01-01 06:00:00    4.0
2015-01-01 07:00:00    4.0
2015-01-01 08:00:00    4.0
2015-01-01 09:00:00    NaN
2015-01-01 10:00:00    3.0
2015-01-01 11:00:00    4.0
2015-01-01 12:00:00    4.0

新的数据帧应该基于“3S”进行采样,如果存在“NaN”,也应该考虑到“NaN”,并从找到“NaN”记录的地方开始采样。

预期输出:

2015-01-01 02:00:00    2.0 -- Sampling after 3S
2015-01-01 03:00:00    2.0 -- Print because NaN has found in Next
2015-01-01 04:00:00    NaN -- print NaN record
2015-01-01 07:00:00    4.0 -- Sampling after 3S
2015-01-01 08:00:00    4.0 -- Print because NaN has found in Next
2015-01-01 09:00:00    NaN -- print NaN record
2015-01-01 12:00:00    4.0 -- Sampling after 3S

标签: pythonpandasdataframe

解决方案


一种方法是用 0 填充 NA:

df['Col_of_Interest'] = df['Col_of_Interest'].fillna(0)

然后对系列进行重新采样:(如果 datetime 是您的索引)

series.resample('30S').asfreq()

推荐阅读