【问题标题】:How to replace outliers with NaN while keeping row intact using pandas in python?如何用 NaN 替换异常值,同时在 python 中使用 pandas 保持行完整?
【发布时间】:2019-09-12 00:53:15
【问题描述】:

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

我已经能够找到异常值并将它们替换为 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 而不是整行?

谢谢

【问题讨论】:

    标签: python-3.x pandas nan outliers


    【解决方案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

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

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

      无需遍历列。

      但是,我建议您使用适当的统计数据来定义异常值,而不是 &lt;= 0

      您可以使用quantiles 喜欢:

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

      【讨论】:

        【解决方案3】:

        使用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])
        

        【讨论】:

          猜你喜欢
          • 2021-04-13
          • 2022-10-05
          • 2021-06-22
          • 1970-01-01
          • 1970-01-01
          • 2021-09-16
          • 2016-06-25
          • 2019-07-12
          • 2023-03-04
          相关资源
          最近更新 更多