Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.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 如何对每个列使用apply()函数及其相应的平均值?_Python_Pandas_Dataframe - Fatal编程技术网

Python 如何对每个列使用apply()函数及其相应的平均值?

Python 如何对每个列使用apply()函数及其相应的平均值?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个如下所示的数据帧: rowid user_id col_2 bias 0 1 0 2.1 1 2 2 2.5 2 3 3 3.6 3 1 0 2.8 4 2 2 1.5 5 3 3 3.2 现在我想让‘bias’列成为相应用户id的平均值

我有一个如下所示的数据帧:

  rowid  user_id  col_2   bias
  0        1      0       2.1
  1        2      2       2.5
  2        3      3       3.6
  3        1      0       2.8
  4        2      2       1.5
  5        3      3       3.2
现在我想让‘bias’列成为相应用户id的平均值,就像一个唯一用户id的平均值一样:

 rowid  user_id  col_2   bias
  0        1      0       2.1
  3        1      0       2.8
致:


使用
groupby.transform

df['bias'] = df.bias.groupby(df.user_id).transform('mean')

df
#   rowid  user_id  col_2  bias
#0      0        1      0  2.45
#1      1        2      2  2.00
#2      2        3      3  3.40
#3      3        1      0  2.45
#4      4        2      2  2.00
#5      5        3      3  3.40

你已经试过什么了?你能发布你的代码吗?
df['bias'] = df.bias.groupby(df.user_id).transform('mean')

df
#   rowid  user_id  col_2  bias
#0      0        1      0  2.45
#1      1        2      2  2.00
#2      2        3      3  3.40
#3      3        1      0  2.45
#4      4        2      2  2.00
#5      5        3      3  3.40