【问题标题】:Column values becoming NaN after resetting index重置索引后列值变为 NaN
【发布时间】:2023-01-02 00:20:03
【问题描述】:

我已经导入了一个 csv 文件,其中包含有差距的股票数据,因为它是交易日,所以它们是不连续的

ps0pyc=pd.read_csv(r'/Users/swapnilgupta/Desktop/fend/p0.csv')
ps0pyc['Date'] = pd.to_datetime(ps0pyc['Date'], dayfirst= True)
ps0pyc

后来我修改为通过传递以下代码来获取所有缺失的间隙值以获得前向填充值:

ps0pyc.set_index('Date',inplace=True) #setting Date column as index
new_idx = pd.date_range('01-03-2013', '01-03-2022') #creating new index
ps0pyc = ps0pyc.reindex(new_idx) #reindexing
ps0pyc.index.name = 'Date' #setting index name

输出 :

    PORTVAL
Date    
2013-01-03  17.133585
2013-01-04  17.130434
2013-01-05  NaN
2013-01-06  NaN
2013-01-07  17.396581

现在我做了:

ps0pyc.fillna(method='ffill') #filling all NaN values
ps0pyc

输出:

    PORTVAL
Date    
2013-01-03  17.133585
2013-01-04  17.130434
2013-01-05  17.130434
2013-01-06  17.130434
2013-01-07  17.396581
... ...
2021-12-30  203.615507
2021-12-31  201.143990
2022-01-01  201.143990
2022-01-02  201.143990
2022-01-03  204.867302

现在我想让索引回到列 但一旦我这样做

ps0pyc.reset_index(inplace=True)

我明白了

    Date    PORTVAL
0   2013-01-03  17.133585
1   2013-01-04  17.130434
2   2013-01-05  NaN
3   2013-01-06  NaN
4   2013-01-07  17.396581
... ... ...
3283    2021-12-30  203.615507
3284    2021-12-31  201.143990
3285    2022-01-01  NaN
3286    2022-01-02  NaN
3287    2022-01-03  204.867302

我在重置索引代码后尝试了 ffill 但我明白了

ps0pyc.fillna(method='ffill', axis=1)

    Date    PORTVAL
0   2013-01-03  17.133585
1   2013-01-04  17.130434
2   2013-01-05  2013-01-05 00:00:00
3   2013-01-06  2013-01-06 00:00:00
4   2013-01-07  17.396581
... ... ...
3283    2021-12-30  203.615507
3284    2021-12-31  201.14399
3285    2022-01-01  2022-01-01 00:00:00
3286    2022-01-02  2022-01-02 00:00:00
3287    2022-01-03  204.867302

【问题讨论】:

    标签: python pandas python-datetime


    【解决方案1】:

    您需要将其分配回来

    ps0pyc = ps0pyc.fillna(method='ffill')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 2022-08-22
      • 2021-01-30
      • 2020-11-21
      • 2015-07-13
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多