Code Sample, a copy-pastable example if possible
# Your code here
df = pd.read_csv("https://github.com/jennybc/gapminder/raw/master/inst/gapminder.tsv", sep="\t")
df[[1,2]]
Problem description
Current behaviour throws a key error
Expected Output
df[[1,2]] should slice the dataframe based on column index
Output of pd.show_versions()
# Paste the output here pd.show_versions() here
KeyError Traceback (most recent call last)
in ()
----> 1 df[[1,2]]
d:\tuts\ipython\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
1956 if isinstance(key, (Series, np.ndarray, Index, list)):
1957 # either boolean or fancy integer index
-> 1958 return self._getitem_array(key)
1959 elif isinstance(key, DataFrame):
1960 return self._getitem_frame(key)
d:\tuts\ipython\lib\site-packages\pandas\core\frame.py in _getitem_array(self, key)
2000 return self.take(indexer, axis=0, convert=False)
2001 else:
-> 2002 indexer = self.loc._convert_to_indexer(key, axis=1)
2003 return self.take(indexer, axis=1, convert=True)
2004
d:\tuts\ipython\lib\site-packages\pandas\core\indexing.py in _convert_to_indexer(self, obj, axis, is_setter)
1229 mask = check == -1
1230 if mask.any():
-> 1231 raise KeyError('%s not in index' % objarr[mask])
1232
1233 return _values_from_object(indexer)
KeyError: '[1 2] not in index'
Comment From: dsm054
That's not a bug.
That frame has columns with string names. You could use df[["country", "continent"]]
or df.loc[:, ["country", "continent"]]
to select by label, or df.iloc[:, [0, 1]]
to select by position.
Comment From: jreback
full documentation is here: http://pandas.pydata.org/pandas-docs/stable/indexing.html