ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements

from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn import preprocessing
import pandas as pd

iris = datasets.load_iris()

df = pd.DataFrame(iris.data)

df.columns = iris.target_names  # 此处报错

X = preprocessing.scale(df)

pca = PCA(n_components= 2)

pca.fit(X)

print(X)

翻译:

数值错误:长度不匹配:需要轴上有4个元素,新的变量只有三个。

调试:

  1. 在df.columns = iris.target_names处设置断点进行调试
  2. 查看赋值前df数据如下图所示:ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements_第1张图片 df有4列数据,即对应4列列名。  <==> df.columns = 4  
  3. 查看赋值前iris数据如下图所示:ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements_第2张图片图中iris.target_names = 3 
  4. df.columns = 4   iris.target_names = 3  数据维数不匹配 找到错因
  5. 解决办法:使用切片操作如下
    from sklearn.decomposition import PCA
    from sklearn import datasets
    from sklearn import preprocessing
    import pandas as pd
    
    iris = datasets.load_iris()
    
    df = pd.DataFrame(iris.data[:, 0:3]) 
    
    df.columns = iris.target_names
    
    X = preprocessing.scale(df)
    
    pca = PCA(n_components= 2)
    
    pca.fit(X)
    
    print(X)

 此时维度对应,问题解决!ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements_第3张图片

 

你可能感兴趣的:(python,机器学习,开发语言)