python - 如何使用python补充时间序列中缺失的数据?

标签 python pandas dataframe date

我有一个数据框,其中包含一年中某几天的价格,现在我想制作一个更大的数据框,显示从年初到某个特定日期的所有日期。然后使用我在原始数据框中已有的日期的价格,并在没有价格的日期之间填写该日期的最后价格。

举个例子:

df = pd.DataFrame({
    'timestamps': pd.to_datetime(
        ['2021-01-04', '2021-01-07', '2021-01-14', '2021-01-21', '2021-01-28', '2021-01-29', 
'2021-02-04', '2021-02-12', '2021-02-18', '2021-02-25']),
    'LastPrice':['113.4377','115.0741','115.5709','116.5197','116.681','116.4198','117.5749','117.2175',
 '117.0541','117.5977']})

我希望我的新约会系列是这样的

index=pd.date_range('2021-01-01', '2021-02-28')

dfObj = pd.DataFrame(columns=['new_Date','new_LastPrice'])
dfObj['new_Date'] = index

所以,理想情况下我应该有类似以下数据框的东西。(只是顶部)

    new_Date    new_LastPrice
0   2021-01-01  0
1   2021-01-02  0
2   2021-01-03  0
3   2021-01-04  113.4377
4   2021-01-05  113.4377
5   2021-01-06  113.4377
6   2021-01-07  115.0741
7   2021-01-08  115.0741
8   2021-01-09  115.0741
9   2021-01-10  115.0741
10  2021-01-11  115.0741
11  2021-01-12  115.0741
12  2021-01-13  115.0741

请问这里有人能帮我吗?

最佳答案

使用DataFrame.reindex使用 method='ffill':

index=pd.date_range('2021-01-01', '2021-02-28')

dfObj = (df.set_index('timestamps')
           .reindex(index, method='ffill')
           .fillna(0)
           .add_prefix('new_')
           .rename_axis('new_Date')
           .reset_index())
print (dfObj.head(13))
     new_Date new_LastPrice
0  2021-01-01             0
1  2021-01-02             0
2  2021-01-03             0
3  2021-01-04      113.4377
4  2021-01-05      113.4377
5  2021-01-06      113.4377
6  2021-01-07      115.0741
7  2021-01-08      115.0741
8  2021-01-09      115.0741
9  2021-01-10      115.0741
10 2021-01-11      115.0741
11 2021-01-12      115.0741
12 2021-01-13      115.0741

关于python - 如何使用python补充时间序列中缺失的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68588163/

相关文章:

python - 如何使用 Python 将光标移动到 MySQL 中的最后一条记录?

python - 使用 PANDAS 组合数据框并添加文件名

python - 使用 tensorflow 进行增量模型训练

python Pandas TypeError : Cannot compare type 'Timestamp' with type 'float'

python - 重命名类型为RangeIndex的pandas数据框列

python - 对空数据框的 Groupby-Transform 引发异常

python - 以奇怪的方式对 Pandas 数据框进行排序和分组

python - pandas 数据库合并多列未正确合并

python - Python 正则表达式问题中的捕获组

python - 使用 lambda 函数交叉嵌套列表