Python 从groupby数据帧的列中删除异常值

Python 从groupby数据帧的列中删除异常值,python,pandas,Python,Pandas,我有以下数据框l,按code和Month分组: l.head(): Qty Code Month 600003 02 1 06 2 600006 02 1 05 1 07 2 我想通过数量检测异常值,所以我尝试通过IQR: def get_num_outliers(column): q1 = np.percentile(col

我有以下数据框
l
,按
code
Month
分组:

l.head():

                 Qty
  Code    Month 
 600003     02    1
            06    2
 600006     02    1
            05    1
            07    2
我想通过
数量
检测异常值,所以我尝试通过IQR:

def get_num_outliers(column):
q1 = np.percentile(column, 25)
q3 = np.percentile(column, 75)
return ((column<q1) | (column>q3))

l.agg([get_num_outliers])
def get_num_异常值(列):
q1=百分位数(第25列)
q3=百分位数(第75列)
返回((第3列))
l、 agg([get\u num\u outliers])
我似乎没有得到一个有效的答案。 我还是熊猫的初学者,不知道是否有人能帮我。谢谢大家!

def删除异常值(df,col):
def remove_outlier(df, col):
  q1 = df[col].quantile(0.25)
  q3 = df[col].quantile(0.75)

  iqr = q3 - q1
  lower_bound  = q1 - (1.5  * iqr)
  upper_bound = q3 + (1.5 * iqr)

  out_df = df.loc[(df[col] > lower_bound) & (df[col] < upper_bound)]
  return out_df
q1=df[col]。分位数(0.25) q3=df[col]。分位数(0.75) iqr=q3-q1 下限=q1-(1.5*iqr) 上限=q3+(1.5*iqr) out_df=df.loc[(df[col]>下限)和(df[col]<上限)] 返回
感谢您提供了简洁的解决方案。问题是
q1
q3
都等同于
1.0
,这导致了相同的
下限和
上限
!您知道我如何创建一个可视化来手动检测异常值或任何其他解决方案吗?再次感谢。当我查看示例数据时,我发现上限为3.5,下限为-0.5。样本数据中的值不得小于-0.5或大于3.5。您确定数据中存在异常值吗?您可以尝试使用箱线图进行可视化。我想我是在寻找没有异常值的异常值。谢谢你给我正确的方向的小费!您好@specbug,如果我的回答有帮助,请不要忘记。