cluuu
cluuu

Reputation: 45

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?

Upvotes: 1

Views: 53

Answers (2)

sophocles
sophocles

Reputation: 13821

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

Upvotes: 1

Abhishek Kumar
Abhishek Kumar

Reputation: 788

You can do something like this and interchange it whatever value you want to replace it with :

df.groupby('solutionType').mean().T['fixed']

Upvotes: 1

Related Questions