从给定索引中寻找最近的非零对

2024-09-30 14:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧-

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

现在我要计算A列中1,1与B列中0110模式的最近出现次数。 我有0110(colB)中第一个1的索引,这里是4,我得到的答案是-2,因为列a(索引6,7)中的对11后面有2个索引。你知道吗

我对010模式的尝试-

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

Tags: 数据key答案dataframedfindexvalue模式
1条回答
网友
1楼 · 发布于 2024-09-30 14:27:06

我认为这是更好的与numpy列表理解完成:

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])

然后你可以从Apos中找到Bpos中每一个元素的最小值

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]

相关问题 更多 >