简体   繁体   English

使用索引列表从二维数组中获取一维 numpy 数组

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

I have a 2d array (nxm) from which I would like to produce a 1d array (length n) using a list of row-indices of length n.我有一个二维数组(nxm),我想从中使用长度为 n 的行索引列表生成一维数组(长度为 n)。

For instance:例如:


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


I have found a way to do this using a list comprehension (iterating over the columns and the indices simultaneously and picking out the value), but there's surely a numpy function that does this?我已经找到了一种使用列表理解(同时迭代列和索引并挑选出值)来做到这一点的方法,但肯定有一个 numpy 函数可以做到这一点?

试试这个:

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

How about this?这个怎么样?

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]

Iterating by rows and picking a value based on column index is also possible:也可以按行迭代并根据列索引选择一个值:

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

Specifying multiple elements by their indices and putting them in a new array is called "advanced indexing".通过索引指定多个元素并将它们放入新数组中称为“高级索引”。

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