pandas - 使用 2 列在 pandas 中插入股票数据
问题描述
我想做股票报价的插值。我缺少一天的数据(如示例):
import numpy as np
import pandas as pd
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(
{'opening': [0.5, 1.3, np.NaN, 4, 5, 1],
'closing': [0, 1, np.NaN, 2, 10, 2]}, index=dates)
opening closing
2013-01-01 0.5 0.0
2013-01-02 1.3 1.0
2013-01-03 NaN NaN
2013-01-04 4.0 2.0
2013-01-05 5.0 10.0
2013-01-06 1.0 2.0
我需要有效插值 NaN 的方法,即closing
of 2013-01-02
is opening
of2013-01-03
和opening
of 2013-01-04
is closing
of 2013-01-03
。期望的输出:
2013-01-01 0.5 0.0
2013-01-02 1.3 1.0
2013-01-03 1.0 4.0
2013-01-04 4.0 2.0
2013-01-05 5.0 10.0
2013-01-06 1.0 2.0
我试图使用应用,但它只有关于当前行的信息。我需要访问上一行和下一行。
解决方案
使用DataFrame.assign
因为有必要通过向前或向后填充“并行”来替换 mssing 值:
df = df.assign(opening = df['opening'].fillna(df['closing'].ffill()),
closing = df['closing'].fillna(df['opening'].bfill()))
print (df)
opening closing
2013-01-01 0.5 0.0
2013-01-02 1.3 1.0
2013-01-03 1.0 4.0
2013-01-04 4.0 2.0
2013-01-05 5.0 10.0
2013-01-06 1.0 2.0
推荐阅读
- php - 使用队列时,Laravel 作业中的 SoapClient 在一段时间后“无法连接到主机”:工作
- java - 选择项目时如何删除BottomnavigationView的标题?// 安卓
- c# - 将列表中的对象转换为字符串
- django - 从应用程序跨站点范围的页脚加载数据
- angular - 有没有一种简单的方法可以在 Angular 中显示日期时间的倒计时?
- html - 如何在提交时以 Angular 7 反应形式应用验证?
- awk - 基于列的前两个字母进行过滤
- r - 如何删除不满足所有条件的所有行(每组)?
- go - 哪些构建约束子句用于区分 32 位和 64 位整数?
- spring-boot - Elasticsearch - must(QueryBuilders.rangeQuery) 和 mustNot(QueryBuilders.existsQuery) 一次不工作