Python数据框:根据先前的行值选择行

时间:2018-09-15 11:04:06

标签: python pandas dataframe

我有以下Python数据框对象df:

   1_count  136088194_count  136088202_count  Label
1  0.0      0.0              0.0              False
2  0.0      0.0              0.0              False
3  0.0      0.0              0.0              True 
4  0.0      0.0              0.0              False
5  0.0      0.0              0.0              False
6  0.0      0.0              0.0              True 
7  6.0      0.0              0.0              False
8  0.0      0.0              0.0              False
9  0.0      0.0              0.0              False

我想创建一个新的数据框,其中包含最后一列中“标签”值“真”之前出现的所有行。

在此示例中,将是第2行和第5行。

结果应如下所示:

   1_count  136088194_count  136088202_count  Label
2  0.0      0.0              0.0              False
5  0.0      0.0              0.0              False

我知道我可以通过以下方式访问第3行和第6行:

df = df.loc[df['Label']==True]

但是如何将数据框移至前几行?

1 个答案:

答案 0 :(得分:1)

一种方法是使用shift

df = df.loc[df.Label.shift(-1)==True]
print(df)

# Output

   1_count  136088194_count 136088202_count   Label
2   0.0          0.0             0.0          False
5   0.0          0.0             0.0          False
相关问题