I have a DataFrame in Pandas with a column 'register'
which can be either 0 or some positive number, I want to create a new column 'Working'
which is 1 if that row in 'register'
or any of the 7 previous ones is not 0. I tried iterating over them but as it is a big DataFrame it works extremely slow. This is my code:
df['working'] = 0
for i in range(len(df['register'])):
if df['register'][i] != 0 or \
(i>1 and df['register'][i-1] != 0) or\
(i>2 and df['register'][i-2] != 0) or\
(i>3 and df['register'][i-3] != 0) or\
(i>4 and df['register'][i-4] != 0) or\
(i>5 and df['register'][i-5] != 0) or\
(i>6 and df['register'][i-6] != 0):
df['working'][i] = 1
else:
df['working'][i] = 0
I also tried using this and looked like this:
df['working']=df['register'].apply(lambda x: 1 if x!=0 or x.shift(1)!=0 or x.shift(2)!=0 or x.shift(3)!=0 or x.shift(4)!=0 or x.shift(5)!=0 or x.shift(6)!=0 else 0)
But I got:
AttributeError: 'float' object has no attribute 'shift'
Is there a better way to do this using pandas?
Thanks in advance.