【问题标题】:KeyError: '[ ...... ] not in index'KeyError: '[ ...... ] 不在索引中'
【发布时间】:2018-05-16 01:31:21
【问题描述】:

我正在对我的数据集进行标准化

def standardization(new_df2, labelcol):
    from sklearn.preprocessing import StandardScaler
    labels = new_df2[labelcol]
    del new_df2[labelcol]
    scaled_features = StandardScaler().fit_transform(new_df2.values)
    new_df3 = pd.DataFrame(scaled_features, index = new_df2, columns = 
       new_df2.columns)
    new_df3[labelcol] = labels

    return new_df3

    labelcol = new_df2.population     #population is one of the columns in dataframe
    new_df3 = standardization(new_df2, labelcol)
    print(new_df3)

我收到以下错误!

KeyError: '[  322.  2401.   496. ...,  1007.   741.  1387.] not in index'

据我所知,322, 2401, ...population 列中的值。

请帮助我如何摆脱这个错误。这是什么意思?

PS:new_df2 = (20640, 14)labelcol.shape = (20640,)

【问题讨论】:

  • 您能否正确缩进您的代码? Python 严重依赖代码缩进,这很可能是您的错误。
  • 我已经编辑了上面的帖子。抱歉,只是在这里我没有正确缩进。无论如何,Keyerror 都存在。
  • [ 322. 2401. 496. ..., 1007. 741. 1387.] 的类型是什么?是列表吗?
  • 是的,它是一个列表

标签: python indexing keyerror


【解决方案1】:

以下代码解决了我的问题

def standardization(new_df2, labelcol):

    dflabel = new_df2[[labelcol]]
    std_df = new_df2.drop(labelcol, 1)
    scaled_features = StandardScaler().fit_transform(std_df.values)
    new_df3 = pd.DataFrame(scaled_features, columns = std_df.columns)
    new_df3 = pd.concat([dflabel, new_df3], axis=1)

    return new_df3  

感谢那些尝试提供帮助的人。

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 2017-11-04
    • 2021-08-23
    • 2016-11-22
    • 2018-04-30
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多