重新索引 Dataframe 的 DatetimeIndex 只给出丢失的数据

Reindex the DatetimeIndex of Dataframe Gives only Missing Data

我 运行 对此一无所知:我正在使用一个在 using

中读取的数据集
import pandas as pd
data = pd.read_csv('data.csv', index_col=[0], names=['Date', 'GDAXI', 'GSPC'], header=0)
data

输出:

             GDAXI              GSPC
Date        
2019-07-23  12490.740234    3005.469971
2019-07-24  12522.889648    3019.560059
2019-07-25  12362.099609    3003.669922
2019-07-26  12419.900391    3025.860107
2019-07-27  12419.900391    3025.860107
... ... ...
2020-07-17  12919.610352    3224.729980
2020-07-20  13046.919922    3251.840088
2020-07-21  13171.830078    3257.300049
2020-07-22  13104.250000    3276.020020
2020-07-23  13103.389648    3256.409912
261 rows × 2 columns

缺少日期(周末),我想用

填充 0
data = data.reindex(dates, fill_value=0)

这给出了以下输出:

          GDAXI GSPC
2019-07-23  0.0 0.0
2019-07-24  0.0 0.0
2019-07-25  0.0 0.0
2019-07-26  0.0 0.0
2019-07-27  0.0 0.0
... ... ...
2020-07-19  0.0 0.0
2020-07-20  0.0 0.0
2020-07-21  0.0 0.0
2020-07-22  0.0 0.0
2020-07-23  0.0 0.0
367 rows × 2 columns

所以出于某种原因 reindex() 将所有内容都解释为缺失数据。

有没有人知道发生了什么事?干杯!

试试这个 -

  1. 使用 pd.to_Datetime 函数将日期列转换为日期时间
  2. 现在,使用数据设置日期为索引=data.set_index('Date')
  3. 使用 timedelta 生成列表'dates',使用开始和结束日期作为参考
  4. 现在应该可以了 - data = data.reindex(dates, fill_value=0)

扩展@mahir kukreja 的回答,这对我有用:

df.index = pd.to_datetime(df.index)
dates = pd.date_range(df.index.min(), df.index.max())
df = df.reindex(dates, fill_value=0)