ubuntu_noob
ubuntu_noob

Reputation: 2365

FInding nearest non zero pair from a given index

I have a dataframe-

df = pd.DataFrame({'A':[1,1,0,0,0,0,1,1,0],'B':[0,0,0,0,1,1,0,0,0]})

Now I want to calculate the nearest occurence of 1,1 in column A wrt to the occurence of 0110 pattern in columnB. I have the index of the 1st 1 in 0110(colB) here 4 and the answer I will get is -2 as the pair 11 in columnA(index 6,7) are 2 index behind.

My attempt for 010 pattern-

anchor = index_value
hnops = min((anchor - df[df.A != 0].index), key=abs) 

Upvotes: 1

Views: 52

Answers (1)

Rocky Li
Rocky Li

Reputation: 5958

I think this is better done with numpy list comprehension:

Apos = [i for i in range(len(df.A)-1) if list(df.A[i:i+2]) == [1,1]]
Bpos = [i+1 for i in range(len(df.B)-3) if list(df.B[i:i+4]) == [0,1,1,0]]

Apos, Bpos
>>> ([0, 6], [4])

And then you can find the minimum to each element in Bpos from Apos by finding the closest

diff = [] 
for i in range(len(Apos)):
    index = np.argmin(np.abs(np.asarray(Bpos) - Apos[i]))
    answer = Bpos[index] - Apos[i]
    diff.append(answer)

diff
>>> [4, -2]

Upvotes: 1

Related Questions