从数据框底部到顶部迭代

时间:2017-04-26 12:15:42

标签: python pandas

我有一个数据框rollArray,如下所示:

rollArray       mavStart     mavEnd buildupStart buildupEnd insampleStart insampleEnd  \
0  2007-01-19 2008-01-04   2008-01-07 2008-02-01    2008-02-04  2008-04-11   
1  2007-01-12 2007-12-28   2007-12-31 2008-01-25    2008-01-28  2008-04-04   
2  2007-01-05 2007-12-21   2007-12-24 2008-01-18    2008-01-21  2008-03-28   
3  2006-12-29 2007-12-14   2007-12-17 2008-01-11    2008-01-14  2008-03-21   
4  2006-12-22 2007-12-07   2007-12-10 2008-01-04    2008-01-07  2008-03-14   
5  2006-12-15 2007-11-30   2007-12-03 2007-12-28    2007-12-31  2008-03-07   
6  2006-12-08 2007-11-23   2007-11-26 2007-12-21    2007-12-24  2008-02-29   
7  2006-12-01 2007-11-16   2007-11-19 2007-12-14    2007-12-17  2008-02-22   
8  2006-11-24 2007-11-09   2007-11-12 2007-12-07    2007-12-10  2008-02-15   
9  2006-11-17 2007-11-02   2007-11-05 2007-11-30    2007-12-03  2008-02-08   
10 2006-11-10 2007-10-26   2007-10-29 2007-11-23    2007-11-26  2008-02-01   
11 2006-11-03 2007-10-19   2007-10-22 2007-11-16    2007-11-19  2008-01-25   
12 2006-10-27 2007-10-12   2007-10-15 2007-11-09    2007-11-12  2008-01-18   
13 2006-10-20 2007-10-05   2007-10-08 2007-11-02    2007-11-05  2008-01-11   
14 2006-10-13 2007-09-28   2007-10-01 2007-10-26    2007-10-29  2008-01-04   

   outsampleStart outsampleEnd  
0      2008-04-14   2008-04-18  
1      2008-04-07   2008-04-11  
2      2008-03-31   2008-04-04  
3      2008-03-24   2008-03-28  
4      2008-03-17   2008-03-21  
5      2008-03-10   2008-03-14  
6      2008-03-03   2008-03-07  
7      2008-02-25   2008-02-29  
8      2008-02-18   2008-02-22  
9      2008-02-11   2008-02-15  
10     2008-02-04   2008-02-08  
11     2008-01-28   2008-02-01  
12     2008-01-21   2008-01-25  
13     2008-01-14   2008-01-18  
14     2008-01-07   2008-01-11 

我想从最底行到顶行迭代数据框,所以做反对:

for index, row in rollArray.iterrows():
    roll = rollArray.index[index]
    print('Roll ', roll)

将产生输出0,1,2,3,4,5,6,7,8,9,10,11,12,13,14。我希望返回的输出是14,13,12,11,10,9,8,7,6,5,4,3,2,1,0。这可能吗?

由于

2 个答案:

答案 0 :(得分:3)

对我而言,添加[::-1]

for index, row in rollArray[::-1].iterrows():
    roll = rollArray.index[index]
print('Roll ', roll)
Roll  14
Roll  13
Roll  12
Roll  11
Roll  10
Roll  9
Roll  8
Roll  7
Roll  6
Roll  5
Roll  4
Roll  3
Roll  2
Roll  1
Roll  0

iloc[::-1]

for index, row in rollArray.iloc[::-1].iterrows():
    roll = rollArray.index[index]
print('Roll ', roll)
Roll  14
Roll  13
Roll  12
Roll  11
Roll  10
Roll  9
Roll  8
Roll  7
Roll  6
Roll  5
Roll  4
Roll  3
Roll  2
Roll  1
Roll  0

答案 1 :(得分:1)

重新索引数据框

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

或:

rollArray = rollArray.iloc[::-1]

然后

for index, row in rollArray.iterrows():
    roll = rollArray.index[index]
    print('Roll ', roll)