Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

python 3.x - Pandas Replace all values of column with the mean of only one group

I have a Pandas dataframe that looks something like this:

  solutionType       attribute
0        fixed       1
1        float       2
2        other       42
3        fixed       55
4        fixed       1010
5        float       2021

I want to replace all of the values in the attribute column with the mean of all the values that have solutionType fixed, so in the example above the result should look like:

  solutionType       attribute
0        fixed       355.33
1        float       355.33
2        other       355.33
3        fixed       355.33
4        fixed       355.33
5        float       355.33

I am able to compute this value using the following

print(df.groupby('solutionType', as_index=False)['attribute'].mean())

and would like to feed the value for fixed into a call of replace() or loc(). How do I do this?

question from:https://stackoverflow.com/questions/66049424/pandas-replace-all-values-of-column-with-the-mean-of-only-one-group

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using your code, you get the mean for all the solutionType's that you have. You can use .loc to get the attribute value for the fixed solutionType:

val = df.groupby('solutionType', as_index=False)['attribute'].mean().set_index('solutionType').loc['fixed','attribute']
df['attribue'] = val

Which prints:


  solutionType  attribute  attribue
0        fixed          1   355.333
1        float          2   355.333
2        other         42   355.333
3        fixed         55   355.333
4        fixed       1010   355.333
5        float       2021   355.333

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...