Search code examples
python-3.xpandasdebuggingtypeerrorkeyerror

How to correctly add the last index value from another df to an empty df? Pandas related


Say I have the following empty df named df_pnl, after being called it produces the following output:

Empty DataFrame
Columns: [PnL, Type of Trade, ROI, Cumulative ROI, Cumulative Investment]
Index: []

If you run df_pnl.index[-1:], it produces the following output:

Index([], dtype='object', name='End Date')

Now, there's another df called df_chosen_trading_pair which shows the following data as output when called:

                         Close Price 
End Date                             
2022-06-25 02:29:59.999        11.21
2022-06-25 02:59:59.999        11.19
2022-06-25 03:29:59.999        11.25
2022-06-25 03:59:59.999        11.37
2022-06-25 04:29:59.999        11.34
                             ...    
2022-06-27 04:59:59.999        10.96
2022-06-27 05:29:59.999        10.80
2022-06-27 05:59:59.999        10.82
2022-06-27 06:29:59.999        10.84
2022-06-27 06:59:59.999        10.88

[106 rows x 1 columns]

If you run df_chosen_trading_pair.index[-1], it produces the following output:

'2022-06-27 06:59:59.999'

If you run type(df_chosen_trading_pair.index[-1]), it produces the following output:

str

I need to add the value of df_chosen_trading_pair.index[-1] to df_pnl.index[-1:] so I end up getting the following output when calling df_pnl:

                         PnL   Type of Trade  ROI  Cumulative ROI  Cumulative Investment
End Date                             
2022-06-27 06:59:59.999  NaN             NaN  NaN             NaN                    NaN

I tried the following lines and none of them worked:

In[124]: df_pnl.index[0:] = df_chosen_trading_pair.index[-1]

TypeError: Index does not support mutable operations

In[125]: df_pnl["End Date"][-1] = df_chosen_trading_pair.index[-1]

KeyError: 'End Date'

May I get some assistance here?


Solution

  • Oops, I ended up getting the solution I was looking for by accident, the following line:

    In [167]: df_pnl.loc[df_chosen_trading_pair.index[-1], :] = None

    Throws:

                             PnL   Type of Trade  ROI  Cumulative ROI  Cumulative Investment
    End Date                             
    2022-06-27 06:59:59.999  NaN             NaN  NaN             NaN                    NaN
    

    Besides, I realized that if I want to add a new row to df_pnl with the same logic, I just have to change the internal value within the array, like this:

    In [167]: df_pnl.loc[df_chosen_trading_pair.index[-2], :] = None

    Throws:

                             PnL   Type of Trade  ROI  Cumulative ROI  Cumulative Investment
    End Date                             
    2022-06-27 06:59:59.999  NaN             NaN  NaN             NaN                    NaN
    
    2022-06-27 06:29:59.999  NaN             NaN  NaN             NaN                    NaN