如何使用NaN替换离群值,同时在python中使用熊猫保持行完整?

时间:2019-04-22 20:54:51

标签: python-3.x pandas nan outliers

我正在处理一个非常大的文件,因此需要消除每一列的异常值。

我已经能够找到异常值并将其替换为NaN,但是它将整个行变成了NaN。我确定我缺少简单的东西,但似乎找不到。

import pandas as pd
import numpy as np
pd.set_option('display.max_rows', 100000)   
pd.set_option('display.max_columns', 10)
pd.set_option('display.width', 1000)

df = pd.read_excel('example sheet.xlsx')   

df = df.replace(df.loc[df['column 2']<=0] ,np.nan)
print(df)

如何仅将一个值转换为NaN而不是整个行?

谢谢

3 个答案:

答案 0 :(得分:1)

为了用NAN更改某些单元格,您应该更改序列值。 取代数据框替换,您应该使用系列替换。

错误的方式:

df = df.replace(df.loc[df['column 2']<=0] ,np.nan)

正确的方法之一:

for col in df.columns:
    s = df[col]
    outlier_s = s<=0
    df[col] = s.where(~outlier_s,np.nan)

where函数:替换条件为False的值。

http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html?highlight=where#pandas.DataFrame.where

答案 1 :(得分:0)

使用np.where根据条件替换值。

# if you have to perform only for single column
df['column 2'] = np.where(df['column 2']<=0, np.nan, df['column 2'])


# if you want to apply on all/multiple columns.
for col in df.columns:
    df[col] = np.where(df[col]<=0, np.nan, df[col])

答案 2 :(得分:0)

您可以执行以下操作:

df.mask(df <= 0, np.nan, axis=1)

无需遍历列。

但是,我建议您使用适当的统计信息来定义离群值,而不要使用<= 0

您可以像这样使用quantiles

df.mask(((df < df.quantile(0.05)) or (df > df.quantile(0.95))), np.nan, axis=1)