以相反的顺序遍历 DataFrame 行索引 [英] Iterating through DataFrame row index in reverse order
问题描述
我知道如何遍历 Pandas DataFrame 的行:
I know how to iterate through the rows of a pandas DataFrame:
for id, value in df.iterrows():
但现在我想以相反的顺序浏览行(id
是数字,但与行号不一致).首先,我想对索引 data.sort(ascending = False)
进行排序,然后运行相同的迭代过程,但它不起作用(它似乎仍然从较小的 id
到更大).
but now I'd like to go through the rows in reverse order (id
is 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 id
to larger).
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
遍历 DataFrame
通常是一个坏主意,除非您使用 Cython.如果你真的需要,你可以使用切片符号来反转 DataFrame
:
Iterating through a DataFrame
is usually a bad idea, unless you use Cython. If you really have to, you can use the slice notation to reverse the 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)
这篇关于以相反的顺序遍历 DataFrame 行索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!