python - 采样数据帧考虑 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
解决方案
一种方法是用 0 填充 NA:
df['Col_of_Interest'] = df['Col_of_Interest'].fillna(0)
然后对系列进行重新采样:(如果 datetime 是您的索引)
series.resample('30S').asfreq()
推荐阅读
- javascript - 推迟 signalR 长轮询请求
- botframework - 如何开始:将 Microsoft bot 框架功能嵌入到具有拖放配置功能的应用程序中?
- reactjs - 创建 React App:安装时未创建 src 和公用文件夹
- regex - 在大数据框中搜索和替换非数字数据的最佳方法
- sql-server - 什么数据类型对应于 Oracle 18C 中的 TIME(在 SQL Server 中)?
- mongodb - 如何将数据推送到数组mongodb
- python - Python 脚本中的未知语法会带来索引错误。你能读一下吗?(并解释一下?)
- android - RecyclerView 不更新
- keyboard - Ctrl + Z 键盘快捷键通常如何实际工作?
- android - 创建 2 个自定义视图时,Android 自定义视图上的 onTouchEvent 不起作用