pandas - 如何从 Pandas 列表中具有匹配值的列中删除行
问题描述
我正在从列中查找异常值并将它们存储在列表中。现在我想从列中删除列表中存在的所有值。怎样才能做到这一点?
这是我查找异常值的功能
outlier=[]
def detect_outliers(data):
threshold=3
m = np.mean(data)
st = np.std(data)
for i in data:
#calculating z-score value
z_score=(i-m)/st
#if the z_score value is greater than threshold value than its a outlier
if np.abs(z_score)>threshold:
outlier.append(i)
return outlier
This is my column in data frame
df_train_11.AMT_INCOME_TOTAL
解决方案
import numpy as np, pandas as pd
df = pd.DataFrame(np.random.rand(10,5))
outlier_list=[]
def detect_outliers(data):
threshold=0.5
for i in data:
#calculating z-score value
z_score=(df.loc[:,i]- np.mean(df.loc[:,i])) /np.std(df.loc[:,i])
outliers = np.abs(z_score)>threshold
outlier_list.append(df.index[outliers].tolist())
return outlier_list
outlier_list = detect_outliers(df)
[[1, 2, 4, 5, 6, 7, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 4, 8],
[0, 1, 3, 4, 6, 8],
[0, 1, 3, 5, 6, 8, 9]]
这样,您可以获得每列的异常值。outlier_list[0]
给你[1, 2, 4, 5, 6, 7, 9]
这意味着第 1,2 行等是第 0 列的异常值。
编辑
简短的回答:
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
df[((df.B - df.B.mean()) / df.B.std()).abs() < 3]
这将过滤只有一列(例如'B')在三个标准偏差内的DataFrame。
推荐阅读
- webview - 电子:分享
使用带有 WebRTC 的 desktopCapture 将内容标记为视频流 - c++ - 动态增长二维数组的行和列
- swift - Swift 泛型树转换为 int
- reactjs - 带有 nextjs 的摩纳哥编辑器
- function - 在 woocommerce 的自定义文本区域中保留用户换行符
- php - 在 Codeigniter 中优化表
- python - 从字典列表中查找最小键值,忽略无值
- powershell - 使用 powershell 在 Windows 10 中将虚拟目录添加到 IIS 站点
- vue.js - v-select vuetify 最大元素数
- python - 使用 h5py 模块将 Python 列表写入 HDF5 文件