Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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 3.x 执行“按平均值分组”,而不将行分组到表中的单个输出行中_Python 3.x_Postgresql_Pandas_Pandas Groupby - Fatal编程技术网

Python 3.x 执行“按平均值分组”,而不将行分组到表中的单个输出行中

Python 3.x 执行“按平均值分组”,而不将行分组到表中的单个输出行中,python-3.x,postgresql,pandas,pandas-groupby,Python 3.x,Postgresql,Pandas,Pandas Groupby,我正在尝试在pandas中执行与postgreSQL'a窗口函数等效的功能。基本上,我希望平均特定组中的列值,并使用结果创建一个新列,而不将行分组为单个输出行 下面是一个例子: data = pd.DataFrame( 'name': ['Steve', 'Jim', 'Anna', 'Susie', 'Greg', 'John', 'Sabrina'], 'salary': [100, 200, 300, 100, 250, 90, 260], 'department': ['Finance'

我正在尝试在pandas中执行与postgreSQL'a窗口函数等效的功能。基本上,我希望平均特定组中的列值,并使用结果创建一个新列,而不将行分组为单个输出行

下面是一个例子:

data = pd.DataFrame(
'name': ['Steve', 'Jim', 'Anna', 'Susie', 'Greg', 'John', 'Sabrina'],
'salary': [100, 200, 300, 100, 250, 90, 260],
'department': ['Finance', 'Finance', 'HR', 'Finance', 'Operations', 'HR', 
'Operations']
})
我可以分组并平均工资

data.groupby('department').agg('mean')
然后左键将结果与原始数据合并

最终结果应包含所有行和列“名称”、“部门”和“部门平均工资”

我想知道是否有一种更快捷、更优雅的方法来做这件事。

听起来你需要


伟大的谢谢!
df['Mean']=df.groupby('department').transform('mean')
df
Out[656]: 
   department     name  salary        Mean
0     Finance    Steve     100  133.333333
1     Finance      Jim     200  133.333333
2          HR     Anna     300  195.000000
3     Finance    Susie     100  133.333333
4  Operations     Greg     250  255.000000
5          HR     John      90  195.000000
6  Operations  Sabrina     260  255.000000