微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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] )

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐