首页 > 解决方案 > Split pandas data frame columns by row value

问题描述

I have a data frame like this:

>df = pd.DataFrame({'A':['M',2,3],'B':['M',2,3],'AA':['N',20,30],'BB':['N',20,30]})
>df = df.rename(columns={df.columns[2]: 'A'})
>df = df.rename(columns={df.columns[3]: 'B'})
>df

  A  B  A  B
0 M  M  N  N
1 2  2  20 20
2 3  3  30 30

and I have to split the data frame vertically by row index 0 = 'M' and 'N':

  A  B
0 M  M
1 2  2
2 3  3

  A  B
0 N  N
1 20 20
2 30 30

The data in the data frame comes from an Excel sheet and the column names are not unique. Thanks for help!

标签: pythonpandasdataframe

解决方案


这应该可以完成工作:

df.loc[:,df.iloc[0, :] == "M"]
df.loc[:,df.iloc[0, :] == "N"]

推荐阅读