Replacing values with groupby means
Asked Answered
L

6

14

I have a DataFrame with a column that has some bad data with various negative values. I would like to replace values < 0 with the mean of the group that they are in.

For missing values as NAs, I would do:

data = df.groupby(['GroupID']).column
data.transform(lambda x: x.fillna(x.mean()))

But how to do this operation on a condition like x < 0?

Thanks!

Lactone answered 7/2, 2013 at 20:51 Comment(0)
D
13

Using @AndyHayden's example, you could use groupby/transform with replace:

df = pd.DataFrame([[1,1],[1,-1],[2,1],[2,2]], columns=list('ab'))
print(df)
#    a  b
# 0  1  1
# 1  1 -1
# 2  2  1
# 3  2  2

data = df.groupby(['a'])
def replace(group):
    mask = group<0
    # Select those values where it is < 0, and replace
    # them with the mean of the values which are not < 0.
    group[mask] = group[~mask].mean()
    return group
print(data.transform(replace))
#    b
# 0  1
# 1  1
# 2  1
# 3  2
Dropforge answered 7/2, 2013 at 21:58 Comment(6)
I was thinking something similar -- .transform(lambda x: x.where(x>=0).fillna(x[x>=0].mean())) but didn't like the repetition of the condition. Your approach bypasses that nicely. The pattern seems common enough that I wonder if pandas should grow a built-in way to support it.Flashcube
@Flashcube I agree it would be nice to see some way to do this (this numpy-foo is impressive!) :)Immedicable
very nice. I haven't seen the use of [~mask] - does the tilda just mean not mask?Cummins
@zach: mask is a Series, which is a subclass of numpy's ndarray class. The tilde is the invert operator when applied to a numpy ndarray. Since mask is of dtype bool (i.e. a boolean array) the inversion is done bit-wise for each element in the array. not mask has a different meaning. This asks Python to reduce mask to its boolean value as a whole object and then take the negation. Numpy arrays refuse to be characterized as True or False. not mask raises a ValueError.Dropforge
Word of warning: Your custom function should not modify the group in-place. It should make a copy, and modify that instead. See pandas.pydata.org/docs/reference/api/…Spathic
What does the ~ sign mean in front of the mask parameter?Trophic
I
3

Here's one way to do it (for the 'b' column, in this boring example):

In [1]: df = pd.DataFrame([[1,1],[1,-1],[2,1],[2,2]], columns=list('ab'))
In [2]: df
Out[2]: 
   a  b
0  1  1
1  1 -1
2  2  1
3  2  2

Replace those negative values with NaN, and then calculate the mean (b) in each group:

In [3]: df['b'] = df.b.apply(lambda x: x if x>=0 else pd.np.nan)
In [4]: m = df.groupby('a').mean().b

Then use apply across each row, to replace each NaN with its groups mean:

In [5]: df['b'] = df.apply(lambda row: m[row['a']]
                                       if pd.isnull(row['b'])
                                       else row['b'],
                           axis=1) 
In [6]: df
Out[6]: 
   a  b
0  1  1
1  1  1
2  2  1
3  2  2
Immedicable answered 7/2, 2013 at 21:51 Comment(2)
I see, by applying that lambda function I can make them nans! Then couldn't I just use the .fillna line I wrote in my question? Your second .apply seems unnecessary.Lactone
@Lactone I couldn't get that line to work for me, but perhaps that is a better way :)Immedicable
U
2

I had the same issue and came up with a rather simple solution

func = lambda x : np.where(x < 0, x.mean(), x)

df['Bad_Column'].transform(func)

Note that if you want to return the mean of the correct values (mean based on positive values only) you'd have to specify:

func = lambda x : np.where(x < 0, x.mask(x < 0).mean(), x)
Uttermost answered 14/11, 2017 at 11:42 Comment(0)
J
1

There is a great Example, for your additional question.

df = pd.DataFrame({'A' : [1, 1, 2, 2], 'B' : [1, -1, 1, 2]})
gb = df.groupby('A')
def replace(g):
   mask = g < 0
   g.loc[mask] = g[~mask].mean()
   return g
gb.transform(replace)

Link: http://pandas.pydata.org/pandas-docs/stable/cookbook.html

Jigsaw answered 25/5, 2017 at 21:48 Comment(1)
Ahh, I understand. Your answer doesn't generalize to to more complicated dataframes. Doesn't matter, very smart! I'm going to continue playing around.Fabrication
L
0

Another approach could be:

df.apply(lambda x: df[df['vals'] > 0].groupby('grps')['vals'].mean().loc[x.grps] if x.vals < 0 else x.vals, axis= 1)
Levant answered 10/7 at 16:35 Comment(0)
O
0

Easy-to-remember solution:

df = pd.DataFrame([[1,1],[1,-1],[2,1],[2,2], [2, -5]], columns=list('ab'))
df

   a  b
0  1  1
1  1 -1
2  2  1
3  2  2
4  2 -5

Create groups with positive average values:

replace = df[df.b >0].groupby('a')['b'].mean()
replace

a
1    1.0
2    1.5

Replace negative values:

df.apply(lambda x: replace[x.a] if x.b < 0 else x.b, axis=1)

0    1.0
1    1.0
2    1.0
3    2.0
4    1.5
Omdurman answered 16/7 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.