将字典中高于该值的数字替换为区域平均值

2024-09-22 14:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能来识别数据中的异常值

outliers=[]
strata = []
def detect_outlier(data_1, x):
    outliers.clear()
    threshold=3.5
    mean_1 = np.mean(data_1[x])
    std_1 =np.std(data_1[x])
    
    
    for y in range(len(data_1[x])):
        z_score= (data_1[x][y] - mean_1)/std_1 
        if np.abs(z_score) > threshold:
            strata.append(data_1["Strata"][y])
            outliers.append(data_1[x][y])
            outliers.sort(reverse = True)
    return dict(zip(strata,outliers))

过滤异常值数据(确定为基于区域的字典)后,该函数为我想要的每一列提供这种输出

outlier_food = detect_outlier(df, "food_pc")
print(outlier_food)

{'East Marmara Region': 750.0, 'Southeast Anatolia Region': 733.3333333333334, 'Istanbul Region': 750.0, 'MergedNUTS1': 750.0, 'Mediterranean Region': 1000.0, 'MergedNUTS3': 750.0, 'MergedNUTS2': 733.3333333333334}

我想在这里做的是:我想在我的“food_pc”列(这是一本字典)中使用区域异常值,并根据“地层”列更改“food_pc”列中的异常值,计算如下:

df.groupby(df["Strata"])["food_pc"].mean()

Strata
East Marmara Region          251.034905
Istanbul Region              243.766840
Mediterranean Region         202.460436
MergedNUTS1                  196.630368
MergedNUTS2                  181.313973
MergedNUTS3                  212.930733
Southeast Anatolia Region    196.041308
Name: food_pc, dtype: float64

Tags: 数据dfdatathresholdfoodnpmeanregion