蟒蛇熊猫 如何从数据帧中删除异常值并替换为前面记录的平均值



我有一个 16k 条记录的数据帧和多组国家/地区和其他字段。我已经生成了 a 数据的初始输出,看起来像下面的截图。现在我需要做一些数据清理,操作,删除偏差或异常值,并将其替换为基于某些规则的值。

即在下面,如果没有后来的记录,我如何识别偏斜点(任何大于 1 的值)并将它们替换为接下来两条记录或上一条记录的平均值。(在该组中)

因此,在下面的数据帧中,我想将 IT 第 1 周 1 的 Bill%4 替换为 IT 第 2 周和第 3 周的平均值,因此它是 0.81。

有什么技巧吗?

Country Week    Bill%1  Bill%2  Bill%3  Bill%4  Bill%5  Bill%6
IT     week1    0.94    0.88    0.85    1.21    0.77    0.75
IT     week2    0.93    0.88    1.25    0.80    0.77    0.72
IT     week3    0.94    1.33    0.85    0.82    0.76    0.76
IT     week4    1.39    0.89    0.86    0.80    0.80    0.76
FR     week1    0.92    0.86    0.82    1.18    0.75    0.73
FR     week2    0.91    0.86    1.22    0.78    0.75    0.71
FR     week3    0.92    1.29    0.83    0.80    0.75    0.75
FR     week4    1.35    0.87    0.84    0.78    0.78    0.74
我不知道

有任何内置函数可以做到这一点,但您应该能够自定义它以满足您的需求,不是吗?

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10,5),columns=list('ABCDE'))
df.index = list('abcdeflght')
# Define cutoff value
cutoff = 0.90
for col in df.columns: 
    # Identify index locations above cutoff
    outliers = df[col][ df[col]>cutoff ]
    # Browse through outliers and average according to index location
    for idx in outliers.index:
        # Get index location 
        loc = df.index.get_loc(idx)
        # If not one of last two values in dataframe
        if loc<df.shape[0]-2:
            df[col][loc] = np.mean( df[col][loc+1:loc+3] )
        else: 
            df[col][loc] = np.mean( df[col][loc-3:loc-1] )

最新更新