0
df1.head()

#i got output
#but i got the error when i run following cell  

subset = df1[[1]]

#error:


KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14940/431015837.py in <module>
----> 1 subset = df1[[1]]

~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.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

~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexing.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(

~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexing.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]"

​```
​


Derek O
  • 16,770
  • 4
  • 24
  • 43

1 Answers1

1

You can use the iloc method for the position-based call.

For example:

import pandas as pd

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

Output will be:

   a
0  1
1  2
Tamil Selvan
  • 1,600
  • 1
  • 9
  • 25