假设有一个简单的数据框:
import pandas as pd
a = pd.DataFrame([[0,1], [2,3]])
我可以很容易地切割这个数据框,第一列是a [[0]]
,第二列是a [[1]]
。
现在,让我们来看更复杂的数据框。下面是我的代码的一部分:
frame = pd.DataFrame(range(100), columns=["Variable"], index=["_".join(["loc", str(i)]) for i in range(1, 101)])
frame[1] = [i**3 for i in range(100)]
DataFrame
frame
也是一个 pandas DataFrame。我可以通过 frame[[1]]
获取第二列。但是当我尝试使用 frame[[0]]
时,会出现错误:
Traceback (most recent call last):
File "<ipython-input-55-0c56ffb47d0d>", line 1, in <module>
frame[[0]]
File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python- 3.5.2.amd64\lib\site-packages\pandas\core\frame.py", line 1991, in __getitem__
return self._getitem_array(key)
File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python- 3.5.2.amd64\lib\site-packages\pandas\core\frame.py", line 2035, in _getitem_array
indexer = self.ix._convert_to_indexer(key, axis=1)
File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python- 3.5.2.amd64\lib\site-packages\pandas\core\indexing.py", line 1184, in _convert_to_indexer
indexer = labels._convert_list_indexer(objarr, kind=self.name)
File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python- 3.5.2.amd64\lib\site-packages\pandas\indexes\base.py", line 1112, in _convert_list_indexer
return maybe_convert_indices(indexer, len(self))
File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python- 3.5.2.amd64\lib\site-packages\pandas\core\indexing.py", line 1856, in maybe_convert_indices
raise IndexError("indices are out-of-bounds")
IndexError: indices are out-of-bounds
我仍然可以使用frame.iloc[:,0]
,但问题是为什么我不能使用简单的切片[[]]
?我使用的是WinPython Spyder 3。
frame[['Variable']]
)。 - ayhan