python - 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
解决方案
您收到错误的原因可能是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)
推荐阅读
- angular - 在返回值之前等待 observable 在每个数组中完成
- python - Prolog 嵌套查询
- node.js - Dynamo DB 上的节点 JS 查询使用 IAM 角色永远挂起
- optimization - 复杂的布尔表达式优化,范式?
- java - Jackson序列化XML与根到抽象类
- string - 我有一个字符串,需要将该字符串与 TCL 中的字符串列表进行比较
- node.js - Redis 哨兵连接从 nodeJS 超时
- azure - 当我在 Python 中有瀑布步骤上下文对象时,如何集成 LUIS?
- python - 我需要在发布 python 包时上传额外的文件夹
- osmnx - 没有节点路径