0

I have a problem regarding NumPy arrays.

I cannot get array methods like .T or functions like numpy.concatenate to work with arrays I create:

>>> a=np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> a.T
array([1, 2, 3])
>>> np.concatenate((a,a),axis=0)
array([1, 2, 3, 1, 2, 3])
>>> np.concatenate((a,a),axis=1)
array([1, 2, 3, 1, 2, 3])
>>>

However when I create an array using bult-in functions like rand everything is fine

>>> a=np.random.rand(1,4)
>>> a.T
array([[ 0.75973189],
       [ 0.23873578],
       [ 0.6422108 ],
       [ 0.47079987]])
>>> np.concatenate((a,a),axis=0)
array([[ 0.92191111,  0.50662157,  0.75663621,  0.65802565],
       [ 0.92191111,  0.50662157,  0.75663621,  0.65802565]])

Do you think it has to do with element types (int32 vs float64) ?

I anm running python 2.7 on windows 7

Any help would be greatly appreciated.

Thanks !

1 Answer 1

1

Try:

a = np.random.rand(4)

and then I think you'll find it works the same.

In general with numpy you really need to pay attention to the shape and axes of your arrays. The shapes (4,), (4,1), and (1,4) are all differently and will behave different in most situations.

For example:

a = np.random.rand(4)
print a.shape, a.T.shape  # (4,) (4,)

b = np.random.rand(1,4)
print b.shape, b.T.shape  # (1,4) (4,1)
Sign up to request clarification or add additional context in comments.

3 Comments

I see... But how am I supposed to create a 1x4 array with the values I want so that I will be able to use methods and functions ?
Ok I found it... I have to use ndmin=2 parameter
If you want to use ndmin you can, but it seems like a better idea to me to explicitly state the dimension of the arrays, but just realize that a 1D array is different than a 2D array, even with a single row or column.

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.