我要连续更改值,直到值> 1
我的数据集如下:
Week1 week 2 week 3
Value 0 0 1
Value 0 1 2
我想将0切换为null,直到该行变得大于0。
我怎么能用大熊猫写出来?
答案 0 :(得分:0)
您可以将mask
与2个由&
链接的布尔掩码结合使用,以按位AND
:
print (df)
Week 1 week 2 week 3 week 4 week 5
Value 0 0 1 0 1
Value 0 1 2 0 1
df = df.mask(df.gt(1).cumsum(axis=1).eq(0) & df.eq(0), np.nan)
print (df)
Week 1 week 2 week 3 week 4 week 5
Value NaN NaN 1 NaN 1
Value NaN 1.0 2 0.0 1
详细信息:
按gt
(>)
比较:
print (df.gt(1))
Week 1 week 2 week 3 week 4 week 5
Value False False False False False
Value False False True False False
使用cumsum
作为检查查找值,直到每行的首False
:
print (df.gt(1).cumsum(axis=1))
Week 1 week 2 week 3 week 4 week 5
Value 0 0 0 0 0
Value 0 0 1 1 1
按eq
(==)
比较:
print (df.gt(1).cumsum(axis=1).eq(0))
Week 1 week 2 week 3 week 4 week 5
Value True True True True True
Value True True False False False
比较原始数据:
print (df.eq(0))
Week 1 week 2 week 3 week 4 week 5
Value True True False True False
Value True False False True False
束缚在一起:
print (df.gt(1).cumsum(axis=1).eq(0) & df.eq(0))
Week 1 week 2 week 3 week 4 week 5
Value True True False True False
Value True False False False False