Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

python - numpy get values in col2 given an array of values matching col1

How can I extract values in Col1 whose Col0 matches any values in a numpy array. I have an np array A, idx. Get me all values in Col1 of array A, whose Col0 values are 1 or 4.

A = np.array([[1, 11], [2, 12], [3, 13], [4,14]])

idx = [1, 4]

I can get for 1 value like this.. but I don't know to get for an array of idx.

vals = A[np.where(A[:,0]==4),1]
vals = A[np.where(A[:,0]==4),4]

a) how can I get the values of Col1 in A where Col0 values are 1 or 4 ( matching idx).

expected result = [11,14]

b) how can I get values of Col1 in A where row indices are 1,4 (matching idx)

expected result = [12, 14]

question from:https://stackoverflow.com/questions/66051785/numpy-get-values-in-col2-given-an-array-of-values-matching-col1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1st part:

idx = [1, 4]
A[np.isin(A[:,0], idx), 1]

array([11, 14])

2nd part:

idx = [1, 3]
A[idx,1]

array([12, 14])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...