简体   繁体   English

如何将 pandas 数据框多索引列移动到 2 行

[英]How to move pandas data frame multiindex column into 2 rows

I have an issue with my data frame.我的数据框有问题。 I have a pandas data frame with MultiIndex Columns, so it means that in my data frame header I have tuples like ("A", 123"), ("B", 456"), ("C", 789).我有一个带有 MultiIndex 列的 pandas 数据框,所以这意味着在我的数据框 header 中我有像 ("A", 123"), ("B", 456"), ("C", 789) 这样的元组。 And I would like to create from this tuple 2 rows in the way that data frame will look like:我想以数据框的方式从这个元组创建 2 行:

"A" “一种” "B" “乙” "C" “C”
123 123 456 456 789 789
row row row
row row row
row row row

There are two possibilities for me.我有两种可能性。 I can have a header in 2 rows, or I can have just one header but in 1 row after header, I will have my 2nd tuple element.我可以在 2 行中有一个 header,或者我可以只有一个 header 但在 header 之后的 1 行中,我将有我的第二个元组元素。

Can you help me with that?你能帮我吗? I tried dropping level but it didn't work.我尝试降低水平但它没有用。

If need convert MultiIndex to first 2 rows use MultiIndex.to_frame with transpose and DataFrame.append , last set default columns names:如果需要将 MultiIndex 转换为前 2 行,请使用带转置和MultiIndex.to_frameDataFrame.append ,最后设置默认列名称:

mux = pd.MultiIndex.from_tuples([("A", 123), ("B", 456), ("C", 789)])
df = pd.DataFrame(0, columns=mux, index=[0])
print (df)
    A   B   C
  123 456 789
0   0   0   0

df1 = df.columns.to_frame().T.append(df, ignore_index=True)
df1.columns = range(len(df1.columns))
print (df1)
     0    1    2
0    A    B    C
1  123  456  789
2    0    0    0

If need move only second level select it by DataFrame.iloc and last remove second level by DataFrame.droplevel :如果只需要将二级 select 移动到DataFrame.iloc ,最后通过DataFrame.droplevel移除二级:

df2 = df.columns.to_frame().T.iloc[[1]].append(df, ignore_index=True).droplevel(1, axis=1)
print (df2)
     A    B    C
0  123  456  789
1    0    0    0

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

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