使用numpy.where匹配元素后,如何获取特定数组位置的值?
Solution
To grab the value in the same row but second column where the first element is 'A', you can adjust your code to target the correct column after identifying the matching row(s):
import numpy as np array_string = np.array([['A', 200],['B', 100]]) # Get row indices where 'A' appears in the first column matching_rows = np.where(array_string[:, 0] == 'A')[0] # Extract the second column (index 1) from those rows result = array_string[matching_rows, 1] print(result) # Output: ['200'] (stored as string in your current array setup)
If you prefer to build off your original np.where(array_string == 'A') approach, you can isolate the row indices from the result and select column 1 directly:
indices = np.where(array_string == 'A') result = array_string[indices[0], 1]
Why your original code didn't work
Your current code array_string[np.where(array_string == 'A')] returns the exact element at the indices where 'A' is found (which is (0,0)), so it gives you 'A' instead of the adjacent value. By focusing on the row index and specifying column 1, you pull the value from the same row but second position.
Additional Notes
- If multiple rows have 'A' in the first column, this will return all corresponding values from the second column as a numpy array. If you know there's exactly one match, add
[0]to get a single value:result = array_string[matching_rows, 1][0] - In your current array, numeric values are stored as strings (since numpy uses a uniform dtype for all elements). To work with numeric values directly, consider a structured array:
array_struct = np.array([('A', 200), ('B', 100)], dtype=[('label', 'U1'), ('value', int)]) result = array_struct[array_struct['label'] == 'A']['value'] # Output: array([200], dtype=int64)
内容的提问来源于stack exchange,提问作者user8504877
相关产品推荐
相关产品推荐

