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]
})
I want to see output as shown below
Can someone help please?
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
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]
})
I want to see output as shown below
Can someone help please?
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