如何在两列值之间按行切片pandas数据帧?

时间:2017-10-17 23:24:47

标签: python pandas dataframe filter slice

     A          B    C  D      E    
0  1.0 2013-01-02  1.0  1   test  
1  1.0 2014-01-02  1.0  2    car  
2  1.0 2015-01-02  1.0  3 tested  
3  1.0 2016-01-02  1.0  4  train 

如何基于E列中的值将pandas数据帧切片以包含上述三个连续行,例如:来自' test'经过测试'?

2 个答案:

答案 0 :(得分:1)

IIUC,使用pd.DataFrame.iloc

df.iloc[0:3]

     A           B    C  D       E
0  1.0  2013-01-02  1.0  1    test
1  1.0  2014-01-02  1.0  2     car
2  1.0  2015-01-02  1.0  3  tested

答案 1 :(得分:1)

我不知道为什么我提出这个解决方案,丑陋但是​​工作......

df.iloc[df.index[(df.E=='test').eq(1)].values[0]:df.index[(df.E=='tested').eq(1)].values[0]+1,:]

Out[151]: 
     A           B    C  D       E
0  1.0  2013-01-02  1.0  1    test
1  1.0  2014-01-02  1.0  2     car
2  1.0  2015-01-02  1.0  3  tested