熊猫数据框(如果连续3个数字)

时间:2020-11-08 19:24:17

标签: python pandas

我有一个数据框df

    Price
0    3
1    3
2    3
3    -3
4    3
5    3

我想创建一列TRUE,如果一行中有2个正数

所以输出是

    Price    output
0    3        FALSE
1    3        TRUE
2    3        TRUE
3    -3       FALSE
4    3        FALSE
5    3        TRUE

1 个答案:

答案 0 :(得分:4)

使用.shift(1)查看上一行中的值:

df['two_positive'] = (df['Price'] >= 0) & (df['Price'].shift(1) >= 0)

结果:

    Price   two_positive
0   3       False
1   3       True
2   3       True
3   -3      False
4   3       False
5   3       True