Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在数据帧中将多个列分组为几列_Python_Pandas_Dataframe_Group By_Pandas Groupby - Fatal编程技术网

Python 在数据帧中将多个列分组为几列

Python 在数据帧中将多个列分组为几列,python,pandas,dataframe,group-by,pandas-groupby,Python,Pandas,Dataframe,Group By,Pandas Groupby,我有一个有虚拟变量的数据帧;但是,我想将多个列(100+)分组为几个列。如有任何建议,将不胜感激。谢谢 例如: A_1 | A_2 | A_3| B_1| B_2| B_3| C_1| C_2| C_2| 0 | 0| 1| 0| 0| 0| 0| 0| 0| 0| 1 | 0| 0| 0| 0| 0| 1| 0| 1| 0| 2 | 0| 0| 0| 0| 0

我有一个有虚拟变量的数据帧;但是,我想将多个列(100+)分组为几个列。如有任何建议,将不胜感激。谢谢 例如:

   A_1 | A_2 | A_3| B_1|  B_2|  B_3|  C_1|  C_2|  C_2|
0 |   0|    1|   0|   0|    0|    0|    0|    0|    0|
1 |   0|    0|   0|   0|    0|    1|    0|    1|    0|
2 |   0|    0|   0|   0|    0|    0|    1|    0|    0|
3 |   0|    0|   0|   0|    1|    0|    0|    0|    0|
4 |   1|    0|   0|   0|    0|    0|    0|    0|    0|
5 |   0|    0|   1|   0|    0|    0|    0|    1|    0|
6 |   0|    0|   0|   1|    0|    0|    0|    0|    0|
期望输出:

   A|  B|  C|  
0| 1|  0|  0|      
1| 0|  1|  1|       
2| 0|  0|  1|       
3| 0|  1|  0|       
4| 1|  0|  0|       
5| 1|  0|  1|      
6| 0|  1|  0|     
我试过使用这个代码;但是,我不断遇到错误消息,说缺少列名

categories = {'A':'A','B': 'B','C': 'C'}
    def correct_categories(cols1):
        return [categories[cat] for col1 in cols1 for cat in categories.keys() if col1.startswith(cat)]
        
rslt = df3.groupby(correct_categories(df3.columns),axis=1).sum()
print(rslt)

错误消息:KeyError:'A'

尝试使用
.str.split()
.str.extract
提取第一个零件,然后在
轴=1
上选择
groupby

# also groupby on
# df.columns.str.extract('^([^_]+)', expand=False)
df.groupby(df.columns.str.split('_').str[0], axis=1).sum()
输出:

   A  B  C
0  1  0  0
1  0  1  1
2  0  0  1
3  0  1  0
4  1  0  0
5  1  0  1
6  0  1  0
谢谢如果标题中的字符数超过“u”,如何使用“.str.extract”?例如,“A_AA_1”?