代码之家  ›  专栏  ›  技术社区  ›  dark horse

Pandad-KeyError:列不在索引中

  •  -1
  • dark horse  · 技术社区  · 6 年前

    我有一个在groupby函数中有列列表的Dataframe。我出错了

    KeyError : "['Type1'] not in index"
    

    temp_v1 = temp_df.groupby(level, as_index = False).sum()[[level, 'Type1', 'Type2','Type3', 'Type4', 'Type5']]
    

    有谁能告诉我上面的数据框哪里出了问题。谢谢。。

    1 回复  |  直到 6 年前
        1
  •  2
  •   jezrael    6 年前

    我猜问题是字符串列 Type1 :

    level = 'F'
    temp_df = pd.DataFrame({
             'Type1':list('abcdef'),
             'Type2':[4,5,4,5,5,4],
             'Type3':[7,8,9,4,2,3],
             'Type4':[1,3,5,7,1,0],
             'Type5':[5,3,6,9,2,4],
             'col':[5,3,6,9,2,4],
             'F':list('aaabbb')
    })
    
    print (temp_df.dtypes)
    Type1    object
    Type2     int64
    Type3     int64
    Type4     int64
    Type5     int64
    col       int64
    F        object
    dtype: object
    

    sum 类型1 is excluded, because not numeric

    cols = [level, 'Type1', 'Type2','Type3', 'Type4', 'Type5']
    temp_v1 = temp_df.groupby(level, as_index = False)[cols].sum()
    print (temp_v1)
       F  Type2  Type3  Type4  Type5
    0  a     13     24      9     14
    1  b     14      9      8     15
    

    另一个问题是列名输入错误或空白,您可以通过将列名转换为 list :

    print (temp_df.columns.tolist())
    ['Type1', 'Type2', 'Type3', 'Type4', 'Type5', 'col', 'F']