代码之家  ›  专栏  ›  技术社区  ›  kms

KeyError:“[['col label 1','col label 2']]都不在[列]中”

  •  0
  • kms  · 技术社区  · 5 年前

    我正在尝试使用 .loc . 根据熊猫文献, https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html , loc先生 似乎是用例的正确索引器。

    原始数据帧和带标签的列是否存在:

    enter image description here

    列标签是动态构造的,并作为列表传递给数据帧切片。

    # Create dictionaries 
    prop_dict = dict(zip(df_list.id, df_list.Company))
    city_dict = dict(zip(df_list.id, df_list.city))   
    
    # Lookup keys (property ids) from prop_dict
    propKeys = getKeysByValue(prop_dict, landlord)
    cityKeys = getKeysByValue(city_dict, market)
    
    prop_list = list(set(propKeys) & set(cityKeys))
    print(prop_list)
    
    [19, 27]
    
    # Slice dataframe 
    df_temp = df_t.loc[:, prop_list]
    

    但是,这会抛出一个错误 KeyError: 'None of [[19, 27]] are in the [columns]'

    Traceback (most recent call last):
      File "/Platform/Deploy/tabs/market.py", line 279, in render_table
        result = top_leads(company, market)
      File "/Platform/Deploy/return_leads.py", line 86, in top_leads
        df_temp = df_matrix.loc[:, prop_list]
      File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1472, in __getitem__
        return self._getitem_tuple(key)
      File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 890, in _getitem_tuple
        retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
      File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1901, in _getitem_axis
        return self._getitem_iterable(key, axis=axis)
      File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1143, in _getitem_iterable
        self._validate_read_indexer(key, indexer, axis)
      File "/anaconda3/lib/python3.7/site-packages/pandas/core/indexing.py", line 1206, in _validate_read_indexer
        key=key, axis=self.obj._get_axis_name(axis)))
    KeyError: 'None of [[19, 27]] are in the [columns]'
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Dnorious    5 年前

    列“19”和“27”是否可能位于第19列和第27列,这就是为什么它第一次给出适当的结果,因为“names”19和27是整数值。如果你想把它作为一个列表传递,那么在列的名称周围就需要有''s',这意味着它应该是['19','27'],而不是[19,27]