Home > Net >  How to merge two columns of a pivot_table from pandas in python?
How to merge two columns of a pivot_table from pandas in python?

Time:11-15

I obtained a dataframe using pd.pivot_table, that looks this

    foo      bar      
Cond1     60   65    60    65
Cond2                      
50        200  210  16.7  15.2
100       200  210  14.9  13.5

I need to get an output that looks this by merging the foo and bar columns

           foo(bar)      
    Cond1     60          65
    Cond2                      
    50        200(16.7)  210(15.2)
    100       200(14.9)  210(13.5)  
    

Is this possible in python using only pandas or numpy or internal libraries?

CodePudding user response:

Solution for no MultiIndex in ouput with DataFrame.xs, casting to strings and last join by :

df1 = df.xs('foo', axis=1, level=0).astype(str)
df2 = df.xs('bar', axis=1, level=0).astype(str)

df = df1   '('   df2   ')'

Solution with MultiIndex:

df1 = df.xs('foo', axis=1, level=0, drop_level=False).astype(str)
df2 = df.xs('bar', axis=1, level=0, drop_level=False).astype(str)

df = df1.rename(columns={'foo':'foo(bar)'}) '('  df2.rename(columns={'bar':'foo(bar)'})  ')'
  • Related