从numpy中的矩阵访问元素

时间:2017-04-05 02:20:11

标签: python numpy

我有一个矩阵A mXn和一个大小为m的数组 该数组表示必须从A索引的列索引。 所以,一个例子

production:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
      options:
        raise_not_found_error: false
        belongs_to_required_by_default: false
        consistency: :strong

我想要的输出是

A = [[ 1,2,3],[1,4,6],[2,9,0]] indices = [0,2,1] (矩阵A每行的相应值)

这是一种矢量化方式。 感谢

2 个答案:

答案 0 :(得分:2)

使用advanced indexing

A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])
indices = np.array([0,2,1])

# here use an array [1,2,3] to represent the row positions, and combined with indices as
# column positions, it gives an array at corresponding positions (1, 0), (2, 2), (3, 1)
A[np.arange(A.shape[0]), indices]
# array([1, 6, 9])

答案 1 :(得分:1)

A = np.array([[ 1,2,3],[1,4,6],[2,9,0]])

indices = [0,2,1]
m=range(0,A.shape[0])
for b in zip(m,indices):
    print A[b]

output:
1
6
9