Faheem Mitha
Faheem Mitha

Reputation: 6326

returning subarrays with the same dimensions when looping over numpy array

Consider the following convenient looping idiom.

import numpy

print "shape of"
x = numpy.array([['a', 'b'], ['c', 'd']])
print x
print "is", x.shape
for row in x:
    print "shape of", row, "is", row.shape

This gives

shape of
[['a' 'b']
 ['c' 'd']]
is (2, 2)
shape of ['a' 'b'] is (2,)
shape of ['c' 'd'] is (2,)

My question is, can one preserve the convenient for row in x idiom while returning arrays which have shape (2,1), in this case? Thanks. A function which converts the shape of the subarray from (2,) to (2,0) would be fine. E.g.

for row in x:
    print "shape of", somefunc(row), "is", row.shape

returning

shape of ['a' 'b'] is (2,1)

Upvotes: 1

Views: 166

Answers (2)

talonmies
talonmies

Reputation: 72349

You can use numpy.expand_dim to increase the rank of any numpy array:

In [7]: x=np.array([1,2,3,4])

In [8]: x.shape
Out[8]: (4,)

In [9]: np.expand_dims(x,axis=-1).shape
Out[9]: (4, 1)

Upvotes: 2

Woltan
Woltan

Reputation: 14023

I don't see why you would want that but you could give this a try:

for row in x:
    print "shape of", row, "is", numpy.reshape(row, (1, row.size)).shape

In my optinion, a 1d-array is easier to handle. So it does not make much sense to me to reshape it to a "1d-matrix".

Upvotes: 1

Related Questions