【问题标题】:Remove outliers from the target column when an independent variable column has a specific value当自变量列具有特定值时,从目标列中删除异常值
【发布时间】:2019-09-17 12:55:53
【问题描述】:

我有一个如下所示的数据框(点击下面的链接):

df.head(10)

https://ibb.co/vqmrkXb

当日列的值等于 6 时,我想做的是从目标列 (occupied_pa​​rking_spaces) 中删除异常值,例如使用正态分布 68-95-99.7 规则。

我尝试了以下代码:

df = df.mask((df['occupied_parking_spaces'] - df['occupied_parking_spaces'].mean()).abs() > 2 * df['occupied_parking_spaces'].std()).dropna()

这行代码从整个数据集中删除异常值,无论自变量如何,但我只想从其中 day 值等于 6 的占用的_parking_spacs 列中删除异常值。

我可以做的是创建一个不同的数据框,我将为其删除异常值:

sunday_df = df.loc[df['day'] == 0]

sunday_df = sunday_df.mask((sunday_df['occupied_parking_spaces'] - sunday_df['occupied_parking_spaces'].mean()).abs() > 2 * sunday_df['occupied_parking_spaces'].std()).dropna()

但是通过这样做,我将在一周中的每一天获得多个数据帧,我必须在最后连接,这是我不想做的事情,因为必须有一种方法可以在同一个数据帧内执行此操作.

你能帮帮我吗?

【问题讨论】:

  • 请勿发布代码/数据图片,我们无法复制您的图片。我看到您的数据已经在 Python IDE 中了。只需执行print(df.head(10)),将其复制并粘贴到您的问题中,而不是图片中

标签: python pandas dataframe normal-distribution outliers


【解决方案1】:

已经定义了一些去除异常值的函数,您可以使用np.where 选择性地应用它:

import numpy as np
df = np.where(df['day'] == 0, 
        remove_outliers(df['occupied_parking_spaces']),
        df['occupied_parking_spaces']
     )

【讨论】:

  • 我首先定义了一个函数'def outlier_removal(x): q_95 = x.quantile(0.95) q_5 = x.quantile(0.05) return (x>q_95) | (x
  • 啊,我知道我哪里出错了。它不应该是一个应用——无论你有什么异常函数都应该把整个系列作为它的参数。立即尝试。
  • 我再次测试了代码,它返回了一个数组,而不是在特定条件下删除了异常值的数据帧。我想要的是这样的东西,但没有 1.96 的任意值,而是 2 个西格玛。 'df1 = df[~df.groupby('Data').transform( lambda x: abs(x-x.mean()) > 1.96*x.std()).values]'
  • 我找到了解决方案。 'df = df[~df.groupby('day').transform(lambda x: abs(x-x.mean()) > 2*x.std()).values]'
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
  • 2022-01-22
  • 2020-07-08
  • 1970-01-01
相关资源
最近更新 更多