how do I change my dataframe shape in python

Question:

below is my code

import pandas as pd
import numpy as np

df = pd.DataFrame({'Date' : [np.nan, '2035-12-31', np.nan, '2036-12-31',np.nan, '2037-12-31',np.nan, '2038-12-31'],
                   'Cftype': ["Interest", "Principal", "Interest", "Principal","Interest", "Principal", "Interest", "Principal"],
                   'CF': [12,23,34,89,45,4,54,78]

})

enter image description here

I want to see output as shown below

enter image description here

Can someone help please?

Asked By: TRex

||

Answers:

I think you can do something like this:

df.fillna(method="bfill", inplace=True)
df.pivot_table(values="CF", columns="Cftype", index="Date")

THis looks like a pivot_table, but the tricky part is dealing with your NaN values. You can backfill them in the process

df.pivot_table(index=df['Date'].fillna(method='bfill'),columns='Cftype')

    CF
Cftype      Interest    Principal
Date        
2035-12-31  12          23
2036-12-31  34          89
2037-12-31  45          4
2038-12-31  54          78
Answered By: G. Anderson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.