简体   繁体   English

如何在python中合并来自pandas的pivot_table的两列?

[英]How to merge two columns of a pivot_table from pandas in python?

I obtained a dataframe using pd.pivot_table, that looks this我使用 pd.pivot_table 获得了一个数据框,看起来像这样

    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 列来获得看起来像这样的输出

           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?这在 python 中是否可能仅使用 pandas 或 numpy 或内部库?

Solution for no MultiIndex in ouput with DataFrame.xs , casting to strings and last join by + :解决方案没有MultiIndex与输出中DataFrame.xs ,铸造为字符串,最后由加盟+

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 : 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)'})+ ')'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM