Skip to main content
 首页 » 编程设计

python之使用 Pandas 中的列表沿轴 1 分组

2024年12月31日10youxin

以下内容来自《使用Pandas进行数据分析》:

Each grouping key can take many forms, and the keys do not have to be all of the same type:

  • A list or array of values that is the same length as the axis being grouped

  • A dict or Series giving a correspondence between the values on the axis being grouped and the group names

我尝试了以下方法:

df1 
         1980   1981    1982    1983    1984    1985    1986 
Country                          
Afghanistan 16  39  39  47  71  340 496 
Albania 1   0   0   0   0   0   1 
Algeria 80  67  71  69  63  44  69 
American Samoa  0   1   0   0   0   0   0 
Andorra 0   0   0   0   0   0   2 
 
Grouping_keys_along_axis_1 
['1', '1', '1', '2', '2', '3', '3'] 
 
df1.groupby(Grouping_keys_along_axis_1, axis = 0).sum() 
KeyError: '1' 

这种行为其实符合我对文档的理解,但似乎与我一开始引用的片段不一致。

我们的想法是将前 3 列分组为一组,接下来的 2 列分组为第二组,最后 2 列分组为第三组,然后在每组中应用汇总函数(此处为 sum())沿轴 = 1。

请您参考如下方法:

我认为您需要以下内容:

ga = ['1', '1', '1', '2', '2', '3', '3'] 
 
df.groupby(ga, axis=1).sum() 

输出:

                  1    2    3 
Country                       
Afghanistan      94  118  836 
Albania           1    0    1 
Algeria         218  132  113 
American Samoa    1    0    0 
Andorra           0    0    2 

请注意,这是有效的,因为您的 ga 列表长度等于 df.columns 索引的长度。因此,您使用 ga(分组轴)列表来确定如何对列进行分组。