Python Pandas Dataframe替换低于阈值的值

J-H*_*J-H 3 python dataframe pandas

如何将元素功能元素应用于pandas DataFrame并传递逐列计算值(例如列的分位数)?例如,如果我想替换DataFrame(with NaN)中的值低于列的第80个百分点的所有元素,该怎么办?

def _deletevalues(x, quantile):
if x < quantile:
    return np.nan
else:
    return x

df.applymap(lambda x: _deletevalues(x, x.quantile(0.8)))
Run Code Online (Sandbox Code Playgroud)

使用applymap只允许一个人单独访问每个值并抛出(当然)一个AttributeError: ("'float' object has no attribute 'quantile'

先感谢您.

jez*_*ael 8

用途DataFrame.mask:

df = df.mask(df < df.quantile())
print (df)
     a    b    c
0  NaN  7.0  NaN
1  NaN  NaN  6.0
2  NaN  NaN  5.0
3  8.0  NaN  NaN
4  7.0  3.0  5.0
5  6.0  7.0  NaN
6  NaN  NaN  NaN
7  8.0  4.0  NaN
8  NaN  NaN  6.0
9  7.0  7.0  6.0
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

In [139]: df
Out[139]:
   a  b  c
0  1  7  3
1  1  2  6
2  3  0  5
3  8  2  1
4  7  3  5
5  6  7  2
6  0  2  1
7  8  4  1
8  5  0  6
9  7  7  6
Run Code Online (Sandbox Code Playgroud)

对于所有列:

In [145]: df.apply(lambda x: np.where(x < x.quantile(),np.nan,x))
Out[145]:
     a    b    c
0  NaN  7.0  NaN
1  NaN  NaN  6.0
2  NaN  NaN  5.0
3  8.0  NaN  NaN
4  7.0  3.0  5.0
5  6.0  7.0  NaN
6  NaN  NaN  NaN
7  8.0  4.0  NaN
8  NaN  NaN  6.0
9  7.0  7.0  6.0
Run Code Online (Sandbox Code Playgroud)

或者

In [149]: df[df < df.quantile()] = np.nan

In [150]: df
Out[150]:
     a    b    c
0  NaN  7.0  NaN
1  NaN  NaN  6.0
2  NaN  NaN  5.0
3  8.0  NaN  NaN
4  7.0  3.0  5.0
5  6.0  7.0  NaN
6  NaN  NaN  NaN
7  8.0  4.0  NaN
8  NaN  NaN  6.0
9  7.0  7.0  6.0
Run Code Online (Sandbox Code Playgroud)