这是我的代码:

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'

Why am I getting this error?
How can I fix that?
What is the right way to reverse 100?

推荐答案

data.reindex(index=data.index[::-1])

或者简单地说:

data.iloc[::-1]

将反转您的数据帧,如果您想要一个从下到上的f或循环,您可以这样做:

f或 idx in reversed(data.index):
    print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])

f或 idx in reversed(data.index):
    print(idx, data.Even[idx], data.Odd[idx])

You are getting an err或 because reversed first calls data.__len__() which returns 6. Then it tries to call data[j - 1] f或 j in range(6, 0, -1), and the first call would be data[5]; but in pandas dataframe data[5] means column 5, and there is no column 5 so it will throw an exception. ( see docs )

Python相关问答推荐

Python中的负前瞻性regex遇到麻烦

根据网格和相机参数渲染深度

jit JAX函数中的迭代器

在Pandas 日历中插入一行

如果条件为真,则Groupby.mean()

使用FASTCGI在IIS上运行Django频道

韦尔福德方差与Numpy方差不同

用合并列替换现有列并重命名

Python,Fitting into a System of Equations

Pandas:将多级列名改为一级

Python逻辑操作作为Pandas中的条件

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

使用Python从rotowire中抓取MLB每日阵容

在极中解析带有数字和SI前缀的字符串

如何使用两个关键函数来排序一个多索引框架?

跳过嵌套JSON中的级别并转换为Pandas Rame

如果有2个或3个,则从pandas列中删除空格

查看pandas字符列是否在字符串列中

GPT python SDK引入了大量开销/错误超时

为用户输入的整数查找根/幂整数对的Python练习