1

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)
0

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

That's a neat solution. How does it compare to reshape in generality?
@FaheemMitha Since neither expand_dims nor reshape copies the array to a new location in memory, both approaches are really equivalent. So it comes down to a matter of taste which one you prefer.
@Woltan: Isn't reshape more general?
@FaheemMitha What do you mean with general? Both are valid functions of the numpy library. It is a matter of taste, and what sort of parameters you have at hand, which one you want to use. I for myself use reshape a lot more often. In your case I would suggest using expand_dims since you don`t need to know what the size of the array is...
@Woltan: By general I mean that one applies more generally than the other. The usual meaning of general. As for using reshape, one can always just use .size as you do, so I don't see the problem.
1

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".

3 Comments

Thanks, but I think you meant to write (row.size, 1).
@FaheemMitha Since ['a' 'b'] is a row vector it should be (1, number_of_elements).
You're right. BTW, I have a function that requires a 2d array, so I have no choice but to change the dimension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.