1

Suppose, I have the following data-set as numpy array:

import numpy as np

x = np.array([0, 5, 10, 15, 20, 25, 30])

y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])

and I want to read only values corresponding to x = 20, 25, 30. How can I read that using numpy ?

5 Answers 5

2

numpy.searchsorted can do the job:

idx = np.searchsorted(x,[20,25,30]) 
part = y[idx]

Note that x has to be sorted. In case x is not sorted try:

idx_sort = np.argsort(x)

xsorted = x[idx_sort]
ysorted = y[idx_sort]

idx = np.searchsorted(xsorted, [20,25,30])
part = y[idx]
Sign up to request clarification or add additional context in comments.

Comments

2

We can filter y using zip and list comprehension.

np.array([v for i, v in zip(x, y) if i in [20, 25, 30]])
#array([0.46052632, 0.5       , 0.53947368])

Alternative with pandas.

import pandas as pd
pd.Series(index=x, data=y).loc[[20, 25, 30]].values

Comments

1

An alternative using numpy.any to create the boolean mask:

import numpy as np

x = np.array([0, 5, 10, 15, 20, 25, 30])
y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])

values = [20,25,30]
m = np.any([x==v for v in values], axis=0)

y[m]
array([0.46052632, 0.5       , 0.53947368])

Comments

-1

this code will do that:

import numpy as np

ind = [np.where(x == num)[0] for num in [20, 25, 30]]
corresponding = y[ind]

i believe there is no need to explain, but if you need anything, comment please

Comments

-2

Not with numpy but with a dict:

import numpy as np

x = np.array([0, 5, 10, 15, 20, 25, 30])
y = np.array([0, 0.13157895, 0.31578947, 0.40789474, 0.46052632, 0.5, 0.53947368])

xy_dict = {}

for j, k in zip(x, y):
    xy_dict[j] = k

print(xy_dict)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.