Home > Mobile >  Iterating over the columns of a numpy array and a vector
Iterating over the columns of a numpy array and a vector

Time:02-21

I have a matrix of dimensions n x d and a vector of labels 1 x n.

n = 3
d = 2
data = np.random.rand((n,d))
labels = np.random.choice(1, n)

I want to iterate over the ith column of data and the ith element of labels at the same time. So far, I have:

for i in range(n):
  x = data[i]
  y = labels[i]

  ... do something with them ..

I've tried to use np.nditer to do this, but have trouble getting the vector and matrix to work together nicely:

for x, y in np.nditer([data, labels]):
  ...

ValueError: operands could not be broadcast together with shapes (3,2) (3,) 

CodePudding user response:

In [15]: n = 3
    ...: d = 2
    ...: data = np.random.rand(n, d)
    ...: labels = np.random.choice(10, n)
In [16]: data, labels
Out[16]: 
(array([[0.87013539, 0.66778321],
        [0.63311902, 0.74640742],
        [0.76874321, 0.43470357]]),
 array([6, 8, 1]))

The straight forward zip:

In [17]: for i, j in zip(data, labels):
    ...:     print(i, j)
[0.87013539 0.66778321] 6
[0.63311902 0.74640742] 8
[0.76874321 0.43470357] 1

a working nditer (not that I recommend it):

In [18]: for x, y in np.nditer([data, labels[:, None]]):
    ...:     print(x, y)
0.8701353861218606 6
0.6677832101171755 6
0.6331190219218099 8
0.7464074205732978 8
0.7687432095639312 1
0.43470357108767144 1
  • Related