【发布时间】:2020-03-01 20:45:33
【问题描述】:
目标:绘制特征重要性
错误 1: AttributeError: 'DataFrame' object has no attribute 'source'
错误 2: KeyError: 'source'
在哪里?: names = [data.source[i] for i in indices] OR names = [data['source'] == i for i in指数]
我不是 python 和 pandas 方面的专家,你能帮我更正这段代码吗?以及是否对语法提出建议以避免将来出现类似错误?
代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('data_with_anomalies.csv')
source = pd.DataFrame(data)
target = data['Anomaly']
source = source.drop(columns = ['Anomaly_Tag'])
model = ExtraTreesClassifier()
model.fit(source, target)
print(model.feature_importances_)
importances = model.feature_importances_
# Below chunk is referred from another question on stackoverflow
# Sort feature importances in descending order
indices = np.argsort(importances)[::-1]
得到错误 1,下面一行:
# Rearrange feature names so they match the sorted feature importances
names = [data.source[i] for i in indices]
或者如果我将其更改为以下,我会收到错误 2:
names = [data['source'] == i for i in indices]
plt.figure()
plt.title("Feature Importance")
plt.bar(range(source.shape[1]), importances[indices])
plt.xticks(range(source.shape[1]), names, rotation=90)
plt.show()
【问题讨论】:
-
在这两种情况下,您实际上都是在尝试访问名为“源”的数据框列,但该列不存在。
标签: python python-3.x pandas dataframe matplotlib