不支持将集合作为索引器传递。使用列表代替

问题描述 投票:0回答:2

请有人告诉我为什么我的函数“X = xdf[selected_features]”不起作用。我使用 Windows 11 和 python 3.12。运行时出现此错误(不支持将集合作为索引器传递。请改用列表)

selected_features = {'NDRE_20', 'NDRE_16', 'CSM_20', 'CSM_16', 'EVI2_16',
 'EVI2_20', 'GCVI_16', 'GCVI_20', 'CIred_16', 'CIred_20', 'SCCCI_16',
 'SCCCI_20', 'NDVI_16', 'NDVI_20', 'Sol_ME_1606', 'Sol_ME_2005',
 'SAVI_20', 'SAVI_16', 'NDWI_16', 'NDWI_B_16', 'NDWI_20', 'NDWI_B_20',
 'soil'}
selected_features

y = xdf['yield_1'] # Targeted Values Selection
X = xdf[selected_features]  # Independent Values
print(X)
print(y)

TypeError                               
Cell In[42], line 2
      1 y = xdf['yield_1'] # Targeted Values Selection
----> 2 X = xdf[selected_features]  # Independent Values
      3 print(X)
      4 print(y)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexing.py:2687, in check_dict_or_set_indexers(key)
   2679 """
   2680 Check if the indexer is or contains a dict or set, which is no longer allowed.
   2681 """
   2682 if (
   2683     isinstance(key, set)
   2684     or isinstance(key, tuple)
   2685     and any(isinstance(x, set) for x in key)
   2686 ):
-> 2687     raise TypeError(
   2688         "Passing a set as an indexer is not supported. Use a list instead."
   2689     )
python python-3.x jupyter-notebook jupyter
2个回答
0
投票

只需使用 ['example'] 而不是 {'example'}


0
投票

由于您使用了大括号 {},因此 Python 将“selected_features”视为一个 set。然而,您实际上需要一个list。要定义列表,需要使用方括号[]。修改后的代码:

selected_features = ['NDRE_20', 'NDRE_16', 'CSM_20', 'CSM_16', 'EVI2_16',
 'EVI2_20', 'GCVI_16', 'GCVI_20', 'CIred_16', 'CIred_20', 'SCCCI_16',
 'SCCCI_20', 'NDVI_16', 'NDVI_20', 'Sol_ME_1606', 'Sol_ME_2005',
 'SAVI_20', 'SAVI_16', 'NDWI_16', 'NDWI_B_16', 'NDWI_20', 'NDWI_B_20',
 'soil']

y = xdf['yield_1'] # Targeted Values Selection
X = xdf[selected_features]  # Independent Values
print(X)
print(y)
© www.soinside.com 2019 - 2024. All rights reserved.