Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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 - Fatal编程技术网

Python 熊猫:组加权平均,如何控制输出列的名称?

Python 熊猫:组加权平均,如何控制输出列的名称?,python,pandas,Python,Pandas,我正在使用一个自定义函数进行加权平均 像 df.groupby(['group1','group2'])。应用(加权平均,'val','wt') 回归系列有点像 group1 group2 foo a 8.085493 b 45.610411 c 161.959249

我正在使用一个自定义函数进行加权平均

df.groupby(['group1','group2'])。应用(加权平均,'val','wt')

回归系列有点像

group1                group2
foo                   a              8.085493
                      b             45.610411
                      c            161.959249
                      d             85.923614
                      e             30.953251
Abar                  a             24.000000
                      b             11.000000
                      c             18.723185
但是,加权平均值列没有名称。如何明确命名此列

我不想依赖于列被分配了名称
0
,因为这可能会导致失败。

使用和
reset\u index

df = pd.DataFrame({'a': [1,1,2,2,3,3], 'b': [1,2,3,4,5,6], 'c': [1,4,3,2,1,6]})
df.groupby(['a', 'b']).c.mean()

a  b
1  1    1
   2    4
2  3    3
   4    2
3  5    1
   6    6
使用
重命名

df.groupby(['a', 'b']).c.mean().rename('hello').reset_index()

   a  b  hello
0  1  1      1
1  1  2      4
2  2  3      3
3  2  4      2
4  3  5      1
5  3  6      6
使用“设置自”的答案,您可以将
名称一起使用

df = pd.DataFrame({'a': [1,1,2,2,3,3], 'b': [1,2,3,4,5,6], 'c': [1,4,3,2,1,6]})
df.groupby(['a', 'b']).c.mean().reset_index(name='avg')
输出:

   a    b   avg
0   1   1   1
1   1   2   4
2   2   3   3
3   2   4   2
4   3   5   1
5   3   6   6

不知道那一系列的
reset_index让你命名,+1Glad,它帮助了你@用户3483203