Dheeraj
Dheeraj

Reputation: 11

get results of numpy sub arrays in seperate sub-arrays on performing an operation, without using for loop

The below code checks if each element of sub-arrays is greater than 2 and gives the result in their respective sub-arrays:

2d_array=np.array([[1,2,3,4],[4,56,7,1]])
for elem in 2d_array:
    print(elem[elem[:]>2])

Output:

[3 4]
[ 4 56  7]

Can we do the same without using a for loop, Preferably using numpy functions.

Upvotes: 1

Views: 54

Answers (1)

blue note
blue note

Reputation: 29081

Numpy produces arrays. In your case, each resulting line has a different length, so you can't get an array, just a list of lists.

However, if you want to gather all the values into a 1D array, you can just do

vaulues = array_2d[array_2d > 2]

Upvotes: 1

Related Questions