Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - collapse a pandas MultiIndex

Suppose I have a DataFrame with MultiIndex columns. How can I collapse the levels to a concatenation of the values so that I only have one level?

Setup

np.random.seed([3, 14])
col = pd.MultiIndex.from_product([list('ABC'), list('DE'), list('FG')])
df = pd.DataFrame(np.random.rand(4, 12) * 10, columns=col).astype(int)

print df

   A           B           C         
   D     E     D     E     D     E   
   F  G  F  G  F  G  F  G  F  G  F  G
0  2  1  1  7  5  9  9  2  7  4  0  3
1  3  7  1  1  5  3  1  4  3  5  6  0
2  2  6  9  9  9  5  7  0  1  2  7  5
3  2  2  8  0  3  9  4  7  0  8  2  5

I want the result to look like this:

   ADF  ADG  AEF  AEG  BDF  BDG  BEF  BEG  CDF  CDG  CEF  CEG
0    2    1    1    7    5    9    9    2    7    4    0    3
1    3    7    1    1    5    3    1    4    3    5    6    0
2    2    6    9    9    9    5    7    0    1    2    7    5
3    2    2    8    0    3    9    4    7    0    8    2    5
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...