Home > database >  How can I convert all columns to index in Python?
How can I convert all columns to index in Python?

Time:01-06

Original dataframe

Parent  Family Name  Money A  Money B

Jack    Everdeen     10000    20000
Rita    Lawrence     4000     2000
Amy     Donnie       5000     9000

What I want.

Parent  Family Name  Money     Money

Jack    Everdeen     Money A   10000    
Jack    Everdeen     Money B   20000
Rita    Lawrence     Money A   4000     
Rita    Lawrence     Money B   2000
Amy     Donnie       Money A   5000     
Amy     Donnie       Money B   9000

I tried it with pivot function but it does not work. My code is as follows.

data_1 = [['Jack','Everdeen',10000,20000],['Rita','Lawrence',4000,2000],['Amy','Donnie',5000,9000]]
df_1 = pd.DataFrame(data_1,columns=['Parent','Family Name','Money A','Money B'],dtype=float)
print(df_1)
loading_pivot_table = pd.pivot_table(df_1
                                     ,index = ['Parent','Family Name']
                                     ,columns = ['Parent','Family Name']
                             ,values = ['Money A','Money B']
                            ,fill_value = 0)
#convert pivot table to DataFrame
loading_pivot_table_convert = loading_pivot_table.reset_index()
print(loading_pivot_table_convert)

CodePudding user response:

Melt it

 pd.melt(df_1, id_vars=['Parent','Family Name'], var_name='MoneyCol', value_name='Money').sort_values('Parent',ascending=False)
Out[13]: 
  Parent Family Name MoneyCol    Money
1   Rita    Lawrence  Money A   4000.0
4   Rita    Lawrence  Money B   2000.0
0   Jack    Everdeen  Money A  10000.0
3   Jack    Everdeen  Money B  20000.0
2    Amy      Donnie  Money A   5000.0
5    Amy      Donnie  Money B   9000.0

CodePudding user response:

have you tried set-index?

df.set_index(['a', 'b', 'c'])
  • Related