2016-07-21 84 views
2

是否有一个优雅的解决方案,只打印每个第n行的熊猫数据框?例如,我想只打印每个第二行。打印每个第n行的熊猫数据帧

这可以通过

i = 0 
for index, row in df.iterrows(): 
    if ((i%2) == 0): 
     print(row) 
    i++ 

做,但有一个更Python的方式来做到这一点?

回答

4

切片的DF与步骤PARAM与iloc

print(df.iloc[::2]) 

In [73]: 
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) 
df 

Out[73]: 
      a   b   c 
0 0.613844 -0.167024 -1.287091 
1 0.473858 -0.456157 0.037850 
2 0.020583 0.368597 -0.147517 
3 0.152791 -1.231226 -0.570839 
4 -0.280074 0.806033 -1.610855 

In [77]: 
print(df.iloc[::2]) 

      a   b   c 
0 0.613844 -0.167024 -1.287091 
2 0.020583 0.368597 -0.147517 
4 -0.280074 0.806033 -1.610855