Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 使用Pandas中的列表沿轴1分组_Python_Pandas_Group By - Fatal编程技术网

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

Python 使用Pandas中的列表沿轴1分组,python,pandas,group-by,Python,Pandas,Group By,以下内容摘自“熊猫数据分析”: 每个分组键可以采用多种形式,并且键不必是 所有相同类型: 与所选轴长度相同的值列表或数组 分组 一种指令或序列,给出数据上的值之间的对应关系 正在分组的轴和组名称 我尝试了以下方法: df1 1980 1981 1982 1983 1984 1985 1986 Country Afghanistan 16 39 39 47 71 340 496 Al

以下内容摘自“熊猫数据分析”:

每个分组键可以采用多种形式,并且键不必是 所有相同类型:

  • 与所选轴长度相同的值列表或数组 分组

  • 一种指令或序列,给出数据上的值之间的对应关系 正在分组的轴和组名称

我尝试了以下方法:

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'
ga = ['1', '1', '1', '2', '2', '3', '3']

df.groupby(ga, axis=1).sum()
这种行为实际上符合我对文档的理解,但似乎与我在开头引用的片段不一致


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

我认为您需要以下内容:

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'
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(分组轴)列表来确定如何对列进行分组。

谢谢,我已经尝试过了。基本上我没有规定正确的轴。