0

I obtained a dataframe using pd.pivot_table, that looks like 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 like 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?

1 Answer 1

0

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)'})+ ')'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.