我有一個格式如下的熊貓資料框:

這包含 3 家公司 MSFT、F 和 BAC 每天的股票價格變化百分比。
我想使用 OneClassSVM 計算器來檢測資料是否為例外值。我嘗試了以下代碼,我相信它可以檢測到包含例外值的行。
#Import libraries
from sklearn.svm import OneClassSVM
import matplotlib.pyplot as plt
#Create SVM Classifier
svm = OneClassSVM(kernel='rbf',
gamma=0.001, nu=0.03)
#Use svm to fit and predict
svm.fit(delta)
pred = svm.predict(delta)
#If the values are outlier the prediction
#would be -1
outliers = where(pred==-1)
#Print rows with outliers
print(outliers)
這給出了以下輸出:

然后我想在我的資料框中添加一個新列,其中包括資料是否為例外值。我嘗試了以下代碼,但由于串列的長度不同,因此出現錯誤,如下所示。
condition = (delta.index.isin(outliers))
assigned_value = "outlier"
df['isoutlier'] = np.select(condition,
assigned_value)

鑒于包含例外值的行串列要短得多,您能否告訴我我可以添加此列?
uj5u.com熱心網友回復:
不太清楚您的代碼是什么delta以及df在您的代碼中是什么。我假設它們是相同的資料框。
您可以使用來自 的結果svm.predict,如果不是例外值,我們將其保留為空白 '':
import numpy as np
df = pd.DataFrame(np.random.uniform(0,1,(100,3)),columns=['A','B','C'])
svm = OneClassSVM(kernel='rbf', gamma=0.001, nu=0.03)
svm.fit(df)
pred = svm.predict(df)
df['isoutlier'] = np.where(pred == -1 ,'outlier','')
A B C isoutlier
0 0.869475 0.752420 0.388898
1 0.177420 0.694438 0.129073
2 0.011222 0.245425 0.417329
3 0.791647 0.265672 0.401144
4 0.538580 0.252193 0.142094
.. ... ... ... ...
95 0.742192 0.079426 0.676820 outlier
96 0.619767 0.702513 0.734390
97 0.872848 0.251184 0.887500 outlier
98 0.950669 0.444553 0.088101
99 0.209207 0.882629 0.184912
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347558.html
