【问题标题】:Iterating through DataFrame row index in reverse order [duplicate]以相反的顺序遍历DataFrame行索引[重复]
【发布时间】:2013-04-14 22:41:35
【问题描述】:

我知道如何遍历 pandas DataFrame 的行:

for id, value in df.iterrows():

但现在我想以相反的顺序浏览各行(id 是数字,但与行号不一致)。首先,我想对索引 data.sort(ascending = False) 进行排序,然后运行相同的迭代过程,但它不起作用(它似乎仍然从较小的 id 变为较大)。

我怎样才能做到这一点?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    遍历DataFrame 通常是个坏主意,除非您使用 Cython。如果你真的需要,你可以使用切片符号来反转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)
    

    【讨论】:

    • 为什么“遍历数据框”是个坏主意?你能支持这个说法吗?
    • 我认为是因为它不能向量化计算("parallelize")
    • @root 有什么替代方案?
    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2021-08-17
    • 2018-03-08
    • 2011-01-07
    相关资源
    最近更新 更多