Python 反转pandas.DataFrame的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20444087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:27:16  来源:igfitidea点击:

Right way to reverse pandas.DataFrame?

pythonpandasreverse

提问by Michael

Here is my code:

这是我的代码:

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'])

When I run this code, i get the following error:

当我运行此代码时,出现以下错误:

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 pandas.DataFrame?

为什么我收到这个错误?
我该如何解决?
什么是正确的逆转方法pandas.DataFrame

采纳答案by behzad.nouri

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

or simply:

或者干脆:

data.iloc[::-1]

will reverse your data frame, if you want to have a forloop which goes from down to up you may do:

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

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

or

或者

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

You are getting an error because reversedfirst calls data.__len__()which returns 6. Then it tries to call data[j - 1]for jin 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)

因为你得到一个错误reversed首先调用data.__len__()返回6,然后试图调用data[j - 1]用于jrange(6, 0, -1)和第一个电话会data[5]; 但是在pandas数据框中data[5]表示第5列,并且没有第5列,因此会引发异常。(见文档

回答by user1951

You can reverse the rows in an even simpler way:

您可以以更简单的方式反转行:

df[::-1]

回答by Michael Styrk

This works:

这有效:

    for i,r in data[::-1].iterrows():
        print(r['Odd'], r['Even'])

回答by Cybernetic

None of the existing answers resets the index after reversing the dataframe.

在反转数据帧后,现有的答案都不会重置索引。

For this, do the following:

为此,请执行以下操作:

 data[::-1].reset_index()