FMEZA
FMEZA

Reputation: 51

How to extract the index of a value in a numpy array?

Here is the scenario:

I have the following variables:

val = [('am', '<f8'), ('fr', '<f8')] # val is type numpy.recarray     

am = [12.33, 1.22, 5.43, 15.23]  # am is type numpy.ndarray  

fr = [0.11, 1.23, 2.01, 1.01]   # fr is type numpy.ndarray  

What I need is to detect the index for am = 12.33 and am = 15.23, once extracted (in this case indexes are [0] and [3]), I need to create the new variables:

new_am = [12.33, 15.23] 

new_fr = [0.11, 1.01] 

My question is: Any idea about how to extract the indexes?

I have already used .index and np.where but it seems to have problems since I received an error message for .index:

"AttributeError: 'numpy.ndarray' object has no attribute ".index" 

and for np.where the returning index is nothing array([], dtype=int64)

Thanks for any idea!

Upvotes: 2

Views: 7569

Answers (1)

akuiper
akuiper

Reputation: 214927

You may want the np.in1d which returns an array of boolean to indicate if an element is in another array:

import numpy as np
am = np.array([12.33, 1.22, 5.43, 15.23]) 
fr = np.array([0.11, 1.23, 2.01, 1.01])

index = np.where(np.in1d(am, [12.33, 15.23]))[0]
index
# array([0, 3])

am[index]
# array([ 12.33,  15.23])

fr[index]
# array([ 0.11,  1.01])

Or maybe you have an array with attributes:

new_arr = np.array(zip(am, fr), dtype=val)

index = np.where(np.in1d(new_arr['am'], [12.33, 15.23]))[0]

new_am = new_arr[index]['am']
new_fr = new_arr[index]['fr']

new_am
# array([ 12.33,  15.23])

new_fr
# array([ 0.11,  1.01])

Upvotes: 3

Related Questions