在一维数组“a”中,找到“a”的索引,其中“a”=“b”,其中“b”是“a”的随机值

2024-03-28 21:46:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次尝试使用Python。如果您能就如何使用Python对数据进行后期处理提供任何建议,我将不胜感激。你知道吗

我有一个二维数组,它有两列,由数字组成:ac。另外,我还有1D数组b,它由一些特定的(精确的)值a组成。我想做的是找到c值,其中a == b。我的方法是找到a的索引,其中a == b,然后使用b[a_indexes]。我找不到索引。你知道吗

    'a'    'c'  
     1     20   
     40    70
     83    67
     1054  90

     'b'
      40
      1054

期望输出:

40 70
1054 90

我试过:

a_indexes = a.index(b) 

但它不起作用。你知道吗

我有一个错误:

'numpy.ndarray' object has no attribute 'index'


Tags: 数据方法nonumpyindexobject错误attribute
1条回答
网友
1楼 · 发布于 2024-03-28 21:46:21

我觉得你想做些

import numpy as np

arr = np.array([[1, 20],  [40, 70], [83, 67], [1054,90]])
b = np.array([40, 1054])

output = []
for value in b:
    a_indexes = np.where(arr == value)
    for a_index in a_indexes[0]: # we look where the value was found along first dimension
        output.append(arr[a_index])
# output should be [array([40, 70]), array([1054, 90])]
print(output)

有关索引的详细信息,请查看Is there a NumPy function to return the first index of something in an array?https://thispointer.com/find-the-index-of-a-value-in-numpy-array/

请注意,如果您有列名,则可能不是处理纯numpy数组,而是处理pandas dataframe或其他内容。你知道吗

相关问题 更多 >