簡體   English   中英

使用索引列表從二維數組中獲取一維 numpy 數組

[英]Get 1d numpy array from 2d array using list of indices

我有一個二維數組(nxm),我想從中使用長度為 n 的行索引列表生成一維數組(長度為 n)。

例如:


2d = ([a,b,c],[d,e,f],[g,h,i]) # input array
1d = ([0,2,1]) # row numbers

result = ([a,e,h]) # array of the first row of first column, third row of second column, second row of third column


我已經找到了一種使用列表理解(同時迭代列和索引並挑選出值)來做到這一點的方法,但肯定有一個 numpy 函數可以做到這一點?

試試這個:

print([y[x] for x, y in zip(_1d, _2d)])

這個怎么樣?

import numpy as np
a = np.arange(9).reshape((3,3))
# [0, 1, 2]
# [3, 4, 5]
# [6, 7, 8]
print(a[[0,2,1], np.arange(3)]) # result : [0 7 5]

也可以按行迭代並根據列索引選擇一個值:

print(a[np.arange(3),[0,2,1]]) # result : [0 5 7]

通過索引指定多個元素並將它們放入新數組中稱為“高級索引”。

x = np.array([x for x in 'abcdefghi']).reshape((3,3))

# array([['a', 'b', 'c'],
#        ['d', 'e', 'f'],
#        ['g', 'h', 'i']], dtype='<U1')

d1_indices = np.array([0,1,2])
d2_indices = np.array([0,2,1])

selectx = x[d1_indices, d2_indices]
# array(['a', 'f', 'h'], dtype='<U1')

# selectx[i] = x[d1_indices[i], d2_indices[i]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM