3

我有一个数据框 16k 记录和多组国家和其他领域。我已经生成了 a 数据的初始输出,如下所示。现在我需要进行一些数据清理、操作、删除偏差或异常值,并将其替换为基于某些规则的值。

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

因此,在下面的数据框中,我想用 IT 的第 2 周和第 3 周的平均值替换 1.21 的 IT 第 1 周的 Bill%4,因此它是 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
4

1 回答 1

3

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

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] )
于 2014-01-02T18:24:16.757 回答