pandas 以相反的顺序遍历 DataFrame 行索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16140174/
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
Iterating through DataFrame row index in reverse order
提问by sashkello
I know how to iterate through the rows of a pandas DataFrame:
我知道如何遍历 Pandas DataFrame 的行:
for id, value in df.iterrows():
but now I'd like to go through the rows in reverse order (idis numeric, but doesn't coincide with row number). Firstly I thought of doing a sort on index data.sort(ascending = False)and then running the same iteration procedure, but it didn't work (it seem to still go from smaller idto larger).
但现在我想以相反的顺序浏览行(id是数字,但与行号不一致)。首先我想对索引进行排序data.sort(ascending = False),然后运行相同的迭代过程,但它不起作用(它似乎仍然从较小id到较大)。
How can I accomplish this?
我怎样才能做到这一点?
回答by root
Iterating through a DataFrameis usually a bad idea, unless you use Cython. If you really have to, you can use the slice notation to reverse the DataFrame:
DataFrame除非您使用 Cython,否则遍历 a通常是一个坏主意。如果您真的必须这样做,您可以使用切片符号来反转DataFrame:
In [8]: import pandas as pd
In [9]: pd.DataFrame(np.arange(20).reshape(4,5))
Out[9]:
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
In [10]: pd.DataFrame(np.arange(20).reshape(4,5))[::-1]
Out[10]:
0 1 2 3 4
3 15 16 17 18 19
2 10 11 12 13 14
1 5 6 7 8 9
0 0 1 2 3 4
In [11]: for row in pd.DataFrame(np.arange(20).reshape(4,5))[::-1].iterrows():
...: print row
...:
(3, 0 15
1 16
2 17
3 18
4 19
Name: 3)
(2, 0 10
1 11
2 12
3 13
4 14
Name: 2)
(1, 0 5
1 6
2 7
3 8
4 9
Name: 1)
(0, 0 0
1 1
2 2
3 3
4 4
Name: 0)

