在通过列在数据帧中的位置访问列时,我遇到了关键错误


df1.head()
#i got output
#but i got the error when i run following cell  
subset = df1[[1]]

#错误:


KeyError                                  Traceback (most recent call last)
~AppDataLocalTemp/ipykernel_14940/431015837.py in <module>
----> 1 subset = df1[[1]]
~AppDataLocalProgramsPythonPython310libsite-packagespandascoreframe.py in __getitem__(self, key)
3462             if is_iterator(key):
3463                 key = list(key)
-> 3464             indexer = self.loc._get_listlike_indexer(key, axis=1)[1]
3465 
3466         # take() does not accept boolean indexers
~AppDataLocalProgramsPythonPython310libsite-packagespandascoreindexing.py in _get_listlike_indexer(self, key, axis)
1312             keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)
1313 
-> 1314         self._validate_read_indexer(keyarr, indexer, axis)
1315 
1316         if needs_i8_conversion(ax.dtype) or isinstance(
~AppDataLocalProgramsPythonPython310libsite-packagespandascoreindexing.py in _validate_read_indexer(self, key, indexer, axis)
1372                 if use_interval_msg:
1373                     key = list(key)
-> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
1375 
1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())
KeyError: "None of [Int64Index([1], dtype='int64')] are in the [columns]"
​```
​

您可以使用iloc方法进行基于位置的调用。

例如:

import pandas as pd
df = pd.DataFrame({'a': [1, 2]})
subset = df.iloc[:, [0]]

输出为:

a
0  1
1  2