gudlife
gudlife

Reputation: 480

Get Value From a NumPy Array

import numpy as np

A and B arrays are in good order.

A = np.array(['a','b','c','d','e'])
B = np.array([5,7,3,9,11])

C = np.array(['a','b','k','j','p','x'])

For each element of array C, if that element is in A, get value from B of the same position as B. If not in A, write np.nan.

The expected result would be:

result = np.array([5,7,na,na,na,na])

How is the easeist way of doing it in numPy?

Upvotes: 2

Views: 3749

Answers (1)

unutbu
unutbu

Reputation: 879201

You could use np.in1d(C, A) to determine if C is in A.

In [110]: np.in1d(C, A)
Out[115]: array([ True,  True, False, False, False], dtype=bool)

Then use np.where to select the desired values from B or np.nan:

In [116]: np.where(np.in1d(C, A), B, np.nan)
Out[116]: array([  5.,   7.,  nan,  nan,  nan])

np.where(cond, B, np.nan) returns an array of the same shape as the boolean array cond. The returned array takes a value from B if the corresponding value in cond is True, and is np.nan otherwise.


If len(C) > len(B), and if you would like the final array to contain NaNs for the last len(C)-len(B) values, then you could use:

N = len(B)
result = np.full(len(C), np.nan)
result[:N] = np.where(np.in1d(C[:N], A), B, np.nan)

Upvotes: 4

Related Questions