collapse a pandas MultiIndex

半腔热情 提交于 2019-11-29 05:21:31

you may try this:

In [200]: cols = pd.Series(df.columns.tolist()).apply(pd.Series).sum(axis=1)

In [201]: cols
Out[201]:
0     ADF
1     ADG
2     AEF
3     AEG
4     BDF
5     BDG
6     BEF
7     BEG
8     CDF
9     CDG
10    CEF
11    CEG
dtype: object

Solution

I did this

def collapse_columns(df):
    df = df.copy()
    if isinstance(df.columns, pd.MultiIndex):
        df.columns = df.columns.to_series().apply(lambda x: "".join(x))
    return df

I had to check if its a MultiIndex because if it wasn't, I'd split a string and recombine it with what ever separator I chose in the join.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!