首页 > 解决方案 > python:分位数代码不会改变最大值和最小值

问题描述

删除异常值时,以下代码未进行任何更改。代码可能有什么问题?

import pandas as pd
import numpy as np
import random


df = pd.DataFrame({'price': np.random.randint(0, 100000000, 50000),
                   'col_2':np.random.randint(0, 100000000, 50000)})

print('Max: ', df['price'].max())
print('Min: ', df['price'].min())
Q1 = df['price'].quantile(0.25)
Q3 = df['price'].quantile(0.75)
IQR = Q3 - Q1


df = df[~((df['price'] < (Q1 - 1.5 * IQR)) | (df['price'] > (Q3 + 1.5 * IQR)))]
print(df.shape)
print('Max: ', df['price'].max())
print('Min: ', df['price'].min())

标签: pythondataframeoutliers

解决方案


这是因为您的数据没有任何异常值 - 根据您的定义。
如果您生成一些,如下例所示,您的代码将按照您的预期将它们删除。

df = (pd.DataFrame({'price': np.random.randint(0, 100000000, 50000), 
                    'col_2':np.random.randint(0, 100000000, 50000)}) 
      .append(pd.DataFrame({'price': np.random.randint(100000000, 200000000, 50),  
                            'col_2':np.random.randint(0, 100000000, 50)})) 
      .reset_index(drop=True) 
     )

推荐阅读