vftw
vftw

Reputation: 1677

Get indices greater than value and keep value

I have a 2D array that looks like this:

[[0.1, 0.2, 0.4, 0.6, 0.9]
[0.3, 0.7, 0.8, 0.3, 0.9]
[0.7, 0.9, 0.4, 0.6, 0.9]
[0.1, 0.2, 0.6, 0.6, 0.9]]

And I want to save the indices where the array is higher than 0.6 but I also want to keep the value of that position, so the output would be:

[0, 3, 0.6]
[0, 4, 0.9]
[1, 2, 0.7]

and so on.

To get the indices I did this:

x = np.where(PPCF> 0.6)
high_pc = np.asarray(x).T.tolist()

but how do I keep the value in a third position?

Upvotes: 1

Views: 111

Answers (4)

Ganesh Tata
Ganesh Tata

Reputation: 1195

import numpy as np

arr = np.array([[0.1, 0.2, 0.4, 0.6, 0.9],
    [0.3, 0.7, 0.8, 0.3, 0.9],
    [0.7, 0.9, 0.4, 0.6, 0.9],
    [0.1, 0.2, 0.6, 0.6, 0.9]]) 
rows, cols = np.where(arr > 0.6) # Get rows and columns where arr > 0.6
values = arr[rows, cols] # Get all values > 0.6 in arr
result = np.column_stack((rows, cols, values)) # Stack three columns to create final array
"""
 Result - 
 [ 0.   4.   0.9]
 [ 1.   1.   0.7]
 [ 1.   2.   0.8]
 [ 1.   4.   0.9]
 [ 2.   0.   0.7]
 [ 2.   1.   0.9]
 [ 2.   4.   0.9]
 [ 3.   4.   0.9]]
"""

You can convert result into a list.

Upvotes: 0

amzon-ex
amzon-ex

Reputation: 1744

Simple, no loops:

x = np.where(PPCF > 0.6)                                                 # condition to screen values
vals = PPCF[x]                                                           # find values by indices
np.concatenate((np.array(x).T, vals.reshape(vals.size, 1)), axis = 1)    # resulting array

Feel free to convert it to a list.

Upvotes: 3

Ashwin
Ashwin

Reputation: 76

You could just run a loop along the columns and rows and check if each element is greater than the threshold and save them in a list.

a = [[0.1, 0.2, 0.4, 0.6, 0.9],
[0.3, 0.7, 0.8, 0.3, 0.9],
[0.7, 0.9, 0.4, 0.6, 0.9],
[0.1, 0.2, 0.6, 0.6, 0.9]]

def find_ix(a, threshold = 0.6):
    res_list = []
    for i in range(len(a)):
        for j in range(len(a[i])):
            if a[i][j] >= threshold:
                res_list.append([i, j, a[i][j]])
    return res_list

print("Resulting list = \n ", find_ix(a))

Upvotes: 1

vbhargav875
vbhargav875

Reputation: 887

This should work :

x = np.where(PPCF> 0.6)
high_pc = np.asarray(x).T.tolist()
for i in high_pc:
    i.append(float(PPCF[i[0],i[1]]))

Upvotes: 1

Related Questions