You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:32:55