这是我的代码:
import pandas as pd data = pd.DataFrame({'Odd':[1,3,5,6,7,9], 'Even':[0,2,4,6,8,10]}) for i in reversed(data): print(data['Odd'], data['Even'])
当我运行此代码时,出现以下错误:
Traceback (most recent call last): File "C:\Python33\lib\site-packages\pandas\core\generic.py", line 665, in _get_item_cache return cache[item] KeyError: 5 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\*****\Documents\******\********\****.py", line 5, in <module> for i in reversed(data): File "C:\Python33\lib\site-packages\pandas\core\frame.py", line 2003, in __getitem__ return self._get_item_cache(key) File "C:\Python33\lib\site-packages\pandas\core\generic.py", line 667, in _get_item_cache values = self._data.get(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1656, in get _, block = self._find_block(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1936, in _find_block self._check_have(item) File "C:\Python33\lib\site-packages\pandas\core\internals.py", line 1943, in _check_have raise KeyError('no item named %s' % com.pprint_thing(item)) KeyError: 'no item named 5'
为什么会出现此错误? 我该如何解决? 正确的逆转方法是pandas.DataFrame什么?
pandas.DataFrame
data.reindex(index=data.index[::-1])
或者简单地:
data.iloc[::-1]
将反转您的数据帧,如果您想使for循环从下到上,则可以执行以下操作:
for
for idx in reversed(data.index): print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
要么
for idx in reversed(data.index): print(idx, data.Even[idx], data.Odd[idx])
因为你得到一个错误reversed首先调用data.__len__()返回6,然后试图调用data[j - 1]用于j在range(6, 0, -1)和第一个电话会data[5]; 但在pandas数据框中data[5]表示第5列,而没有第5列,因此它将引发异常。(请参阅文档)
reversed
data.__len__()
data[j - 1]
j
range(6, 0, -1)
data[5]