繁体   English   中英

如何按两列值之间的行对熊猫数据框进行切片?

[英]How to slice a pandas dataframe by rows between two column values?

     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 中的值(例如,从“test”到“tested”)将 Pandas 数据帧切片以包含上述三个连续行?

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

我不知道为什么我想出了这个解决方案,丑陋但有效..

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM