简体   繁体   中英

find specific element with numpy in 2d array

I need your help, I am new to Python so I need to search an array for a specific value in the first column and return the text found in the second column.

dataProject = np.array([
    [1]['text 1'],
    [2]['text 2'],
    [3]['text 3'],
    [4]['text 4'],
    [5]['text 5']
])

a = np.where(dataProject[:,0].astype(int) == 2)
print(a)

in the example it would have to return "text 2", but it returns

(array([0], dtype=int64),)

Assuming you intended to have a 2D array, ie dataProject.ndim = 2, the following line of code returns all values of the second column for which the first column is equal to 2.

dataProject = np.array([[1, 'text 1'],
                        [2, 'text 2'],
                        [3, 'text 3'],
                        [4, 'text 4'],
                        [5, 'text 5']])

a = dataProject[dataProject[:,0].astype(int) == 2, 1]

In this case print(a) will print ['text 2'] . As the comments mentioned, if there should be a unique key-value mapping, then a Dict would be a better choice. If you want only the first instance instead of a list of strings, you could print(a[0]) or do a = dataProject[dataProject[:,0].astype(int) == 2, 1][0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM