首页 > 解决方案 > Python - dask数据框中一系列的模棱两可的真值

问题描述

我正在运行以下代码以检测和打印数据集中的任何异常值:

outliers = []
fields = ['Nums']

nums_df = dd.read_csv("data/mydata.csv", usecols=fields, dtype=float)

def detect_outliers(df):
    threshold = 3
    mean = np.mean(df)
    std = np.std(df)

    for index in df.iterrows():
        z_score = (index - mean) / std
        if abs(z_score) > threshold:
            outliers.append(index)
    return outliers

outliers = detect_outliers(nums_df)

print(outliers)

这会导致以下错误ValueError: The truth value of a Series is ambiguous. Use a.any() or a.all().

在 if 语句中添加 any() 或 all() 可以修复错误,但不出所料会返回不正确的结果。我的意思是如何评估每一行的真值个性以确定它是否满足异常值的阈值?

编辑:尝试iterseries()在返回的系列上使用iterrows()仍然会产生错误:ValueError: Metadata inference failed in sub. AssertionError(<class 'tuple'>,)

for index, series in df.iterrows():
    for s_index in series.iteritems():
        z_score = (s_index - mean) / std
        if abs(z_score) > threshold:
            outliers.append(s_index)
return outliers

标签: pythondataframedask

解决方案


您收到错误的原因可能是mean并且std看起来不是值,而是Series对象。

但是,在您的情况下,您不需要遍历行,只需使用pandas强大的语法创建一个系列。

import pandas as pd
import numpy as np

df = pd.DataFrame({"Nums": np.random.random(10)})
mean = np.mean(df["Nums"])
std = np.std(df["Nums"])
threshold = 0.8
df["outliers"] = (df["Nums"] - mean)/std > threshold

outliers = df[df["outliers"]]
print(outliers)

推荐阅读