Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest index with "True" and calculating the distance (Pandas)

I have a DataFrame like this:

idx Var1 Var2 Var3
0 True False False
1 False True False
2 True False True
3 False False False
4 True False True

I'd like to create three new columns with the distance (from each row) of the closest True, and if that row has a True show 0, so I would get this:

idx Var1 Var2 Var3 distV1 distV2 distV3
0 True False False 0 1 2
1 False True False 1 0 1
2 True False True 0 1 0
3 False False False 1 2 1
4 True False True 0 3 0

I have read all other discussions related to this topic but haven't been able to find an answer for something like this.

like image 778
Carlos Ortega González Avatar asked Dec 30 '25 06:12

Carlos Ortega González


1 Answers

Here is one approach with numpy ops:

for c in df:
    r = np.where(df[c])[0]
    d = abs(df.index.values[:, None] - r)
    df[f'{c}_dist'] = abs(df.index - r[d.argmin(1)])

print(df)

    Var1   Var2   Var3  Var1_dist  Var2_dist  Var3_dist
0   True  False  False          0          1          2
1  False   True  False          1          0          1
2   True  False   True          0          1          0
3  False  False  False          1          2          1
4   True  False   True          0          3          0
like image 190
Shubham Sharma Avatar answered Jan 02 '26 14:01

Shubham Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!