我正在尝试调查我的异常值是数据错误还是异常的真实数据点。 这是我的代码,用于查找其列名和索引号。
outliers = []
for r in df.index:
for c in df.columns:
if (df.loc[r,c]>0.6):
outliers.append([r,c])
此代码有效,但效率低下。有没有更好的办法?离群值截止值为0.6
答案 0 :(得分:1)
脾气暴躁的argwhere
:
np.argwhere(df.values>0.6)
示例:
df = pd.DataFrame(np.random.rand(10).reshape(2,5))
# 0 1 2 3 4
#0 0.002991 0.976504 0.683546 0.506011 0.207941
#1 0.500685 0.738651 0.962306 0.902494 0.791330
np.argwhere(df.values>0.6).tolist()
#[[0, 1], [0, 2], [1, 1], [1, 2], [1, 3], [1, 4]]
如果您不需要索引号(iloc),而是行/列索引的值,则可以使用:
[(df.index[x[0]], df.columns[x[1]]) for x in np.argwhere(df.values>0.6).tolist()]
答案 1 :(得分:1)
您也可以使用stack
和布尔索引:
示例df:
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,10,(5,4)),columns=list('ABCD'))
print(df)
thresh = 6 #change as required
s = df.stack(dropna=False)
print(s[s.gt(thresh)].index.tolist())
[(1, 'A'), (1, 'B'), (2, 'C'), (3, 'A'), (3, 'B'), (4, 'A'), (4, 'B'), (4, 'C')]
outliers = []
for r in df.index:
for c in df.columns:
if (df.loc[r,c]> thresh):
outliers.append([r,c])
print(outliers)
[[1, 'A'], [1, 'B'], [2, 'C'], [3, 'A'], [3, 'B'], [4, 'A'], [4, 'B'], [4, 'C']]