【问题标题】:How to slice a pandas dataframe by rows between two column values?如何按两列值之间的行对熊猫数据框进行切片?
【发布时间】:2018-03-29 18:22:28
【问题描述】:
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 数据框分割为包含上述三个连续行,例如从“测试”到“测试”?
【问题讨论】:
标签:
python
pandas
dataframe
filter
slice
【解决方案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
【解决方案2】:
我不知道为什么要提出这个解决方案,丑陋但有效..
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