python pandas如何从数据框中删除异常值并替换为先前记录的平均值

我有一个数据框16k记录以及多个国家和其他字段组.我已经生成了看起来像下面的snipit的数据的初始输出.现在,我需要进行一些数据清理,操作,消除偏斜或异常值,并根据某些规则将其替换为值.

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

因此,在下面的数据框中,我想将IT第1周的Bill1的Bill4 4(IT1第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] )

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...