我正在尝试使用
.loc
. 根据熊猫文献,
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
,
loc先生
似乎是用例的正确索引器。
原始数据帧和带标签的列是否存在:
列标签是动态构造的,并作为列表传递给数据帧切片。
# 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]'