Home > Mobile >  Column values becoming NaN after resetting index
Column values becoming NaN after resetting index

Time:01-02

I have imported a csv file with stock data which is having gaps , as it is trading days so they are non continuous

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

later on i modified to get all missing gap values to get a forward filled value by passing below code :

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

Output :

    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

Now I did :

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

Output:

    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

Now I wanted to make index back to column but as soon as i do that

ps0pyc.reset_index(inplace=True)

I get this

    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

I tried ffill after the reset index code but i get this

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

CodePudding user response:

You need to assign it back

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