I have a problem accessing the data in a multidimensional numpy-array with python 2.7. The goal is to read multiple values whose positions are stored in a list.
import numpy as np
matrix=np.ones((10,30,5))
positions=[]
positions.append([1,2,3])
positions.append([4,5,6])
for i in positions:
print matrix[i]
What I want is:
print matrix[1,2,3]
But I get:
print [matrix[1], matrix[2], matrix[3]]
Could you please give me a hint for the correct indexing? Thanks!
From indexing docs :
In Python,
x[(exp1, exp2, ..., expN)]
is equivalent tox[exp1, exp2,..., expN];
the latter is just syntactic sugar for the former.
So, instead of passing it a list, pass a tuple to matrix
:
for i in positions:
print matrix[tuple(i)]
Lists are used for picking item at particular indices, ie index arrays :
>>> arr = np.random.rand(10)
>>> arr
array([ 0.56854322, 0.21189256, 0.72516831, 0.85751778, 0.29589961,
0.90989207, 0.26840669, 0.02999548, 0.65572606, 0.49436744])
>>> arr[[0, 0, 5, 1, 5]]
array([ 0.56854322, 0.56854322, 0.90989207, 0.21189256, 0.90989207])
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.