Python 运行出现:pandas attribute error : no attribute ‘Factor‘ found解决方案(转载)

Python 运行出现:pandas attribute error : no attribute ‘Factor’ found解决方案(转载)

一、遇到的问题## 标题

博主在做随机森林的学习运行代码出现一下错误:

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
 
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75
df['species'] = pd.Factor(iris.target, iris.target_names)
df.head()
 
train, test = df[df['is_train']==True], df[df['is_train']==False]
 
features = df.columns[:4]
clf = RandomForestClassifier(n_jobs=2)
y, _ = pd.factorize(train['species'])
clf.fit(train[features], y)
 
preds = iris.target_names[clf.predict(test[features])]
pd.crosstab(test['species'], preds, rownames=['actual'], colnames=['preds'])

错误:

    File "test_iris_with_rf.py", line 9, in 
        df['species'] = pd.Factor(iris.target, iris.target_names)
    AttributeError: 'module' object has no attribute 'Factor'

发现这是因为pandas版本太新了…

pd.Factor(iris.target, iris.target_names)

改为

pd.Categorical.from_codes(iris.target, iris.target_names)

转载自:https://blog.csdn.net/qq_36556893/article/details/82852599

你可能感兴趣的:(机器学习,tensorflow,深度学习)