12

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!

4

4 回答 4

12

使用@AndyHayden 的示例,您可以使用groupby/ transformwith 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
于 2013-02-07T21:58:44.930 回答
3

这是一种方法(对于'b'专栏,在这个无聊的例子中):

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

将这些负值替换为 NaN,然后​​计算b每组的平均值 ( ):

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

然后apply在每一行中使用,用它的组替换每个 NaN 意味着:

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
于 2013-02-07T21:51:08.493 回答
1

我有同样的问题,并想出了一个相当简单的解决方案

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

df['Bad_Column'].transform(func)

请注意,如果您想返回正确值的平均值(仅基于正值的平均值),您必须指定:

func = lambda x : np.where(x < 0, x.mask(x < 0).mean(), x)
于 2017-11-14T11:42:18.503 回答
1

对于您的附加问题,有一个很好的示例。

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)

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

于 2017-05-25T21:48:27.207 回答