Reputation: 475
I want to check for multiple conditions with a where clause in Pandas. Let's say I want the indices of where a row A has the same value as the previous two:
df.new = df.index.where(df.A.eq(df.A.shift(1)) & df.A.eq(df.A.shift(2)))
This works, but when I do it now for more values, e.g. 1 to 10 or some special numbers like 1, 3, 7, 50, I want to do it more efficient than writing them all down.
I tried something like
df.new = df.index.where(df.A.eq(df.A.shift(x)) for x in range(10)))
but this does not work. How can I do this? Thanks!
Upvotes: 1
Views: 70
Reputation: 863166
I think you need numpy.logical_and
with reduce
:
m = np.logical_and.reduce([df.A.eq(df.A.shift(x)) for x in range(1, 11)])
df.new = df.index.where(m)
Upvotes: 2