簡體   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