[Tutor] inserting a vector into an array - numpy Q
Danny Yoo
dyoo at cs.wpi.edu
Tue Jun 10 23:53:48 CEST 2008
> I know there must be a better way to do this with slices, but I can't
> seem to figure it out - I keep getting errors about the need to have the
> same dimensions:
Look at the error message more closely.
ValueError: arrays must have same number of dimensions
What does this mean?
The 1-d array that's being passed in has a different dimension than the 2d
array. If we trust the error message, we should make the two arrays the
same dimension before we pass them to functions that glue these arrays
together.
We want both of them to be two-dimensional. If we look in:
http://www.scipy.org/Numpy_Functions_by_Category
we should see several ways to do this. One way is with reshape:
http://www.scipy.org/Numpy_Example_List_With_Doc#reshape
For example:
########################################
>>> numpy.array([1, 2, 3]).reshape(1, 3)
array([[1, 2, 3]])
>>>
>>>
>>> numpy.append(numpy.array([1, 2, 3]),
... numpy.array([[4, 5, 6],
... [7, 8, 9]]),
... axis=0)
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/lib/python2.5/site-packages/numpy/lib/function_base.py", line
1492, in append
return concatenate((arr, values), axis=axis)
ValueError: arrays must have same number of dimensions
#####################################################
As we expect, this fails. But let's try to reshape the first array into
two dimensions and try again.
#####################################################
>>> numpy.append(numpy.array([1, 2, 3]).reshape(1, 3),
... numpy.array([[4, 5, 6],
... [7, 8, 9]]),
... axis=0)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
########################################
Another way is to use numpy.atleast_2d(), and for your particular example,
it's probably more appropriate than using reshape() on the 1-d array.
####################################################
>>> numpy.atleast_2d(numpy.array([3,1,4,1,5]))
array([[3, 1, 4, 1, 5]])
>>> numpy.atleast_2d(numpy.array([3,1,4,1,5])).shape
(1, 5)
####################################################
See:
http://www.scipy.org/Numpy_Example_List_With_Doc#atleast_2d
More information about the Tutor
mailing list