[Numpy-discussion] Array resize question
Neil Martinsen-Burrell
nmb at wartburg.edu
Tue Jun 16 11:10:42 EDT 2009
On 2009-06-16 09:42 , Cristi Constantin wrote:
> Good day.
> I have this array:
>
> a = array([[u'0', u'0', u'0', u'0', u'0', u' '],
> [u'1', u'1', u'1', u'1', u'1', u' '],
> [u'2', u'2', u'2', u'2', u'2', u' '],
> [u'3', u'3', u'3', u'3', u'3', u' '],
> [u'4', u'4', u'4', u'4', u'4', u'']],
> dtype='<U1')
>
> I want to resize it, but i don't want to alter the order of elements.
>
> a.resize((5,10)) # Will result in
> array([[u'0', u'0', u'0', u'0', u'0', u' ', u'1', u'1', u'1', u'1'],
> [u'1', u' ', u'2', u'2', u'2', u'2', u'2', u' ', u'3', u'3'],
> [u'3', u'3', u'3', u' ', u'4', u'4', u'4', u'4', u'4', u''],
> [u'', u'', u'', u'', u'', u'', u'', u'', u'', u''],
> [u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']],
> dtype='<U1')
>
> That means all my values are mutilated. What i want is the order to be
> kept and only the last elements to become empty. Like this:
> array([[u'0', u'0', u'0', u'0', u'0', u' ', u'', u'', u'', u''],
> [u'1', u'1', u'1', u'1', u'1', u' ', u'', u'', u'', u''],
> [u'2', u'2', u'2', u'2', u'2', u' ', u'', u'', u'', u''],
> [u'3', u'3', u'3', u'3', u'3', u' ', u'', u'', u'', u''],
> [u'4', u'4', u'4', u'4', u'4', u' ', u'', u'', u'', u'']],
> dtype='<U1')
>
> I tried to play with resize like this:
> a.resize((5,10), refcheck=True, order=False)
> # SystemError: NULL result without error in PyObject_Call
>
> vCont1.resize((5,10),True,False)
> # TypeError: an integer is required
>
> Can anyone tell me how this "resize" function works ?
> I already checked the help file :
> http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html
> Thank you in advance.
Resize takes the existing elements and puts them in a new order. This
is its purpose. What you want to do is to stack two arrays together to
make a new array:
In [4]: x = np.random.random((5,5))
In [6]: x.shape
Out[6]: (5, 5)
In [7]: y = np.zeros((5,5))
In [8]: y.shape
Out[8]: (5, 5)
In [10]: z = np.hstack((x,y))
In [11]: z.shape
Out[11]: (5, 10)
In [12]: z
Out[12]:
array([[ 0.72215359, 0.32388934, 0.24858866, 0.40907379, 0.26072476,
0. , 0. , 0. , 0. , 0. ],
[ 0.59085241, 0.88075534, 0.2288914 , 0.49258006, 0.28175061,
0. , 0. , 0. , 0. , 0. ],
[ 0.50355137, 0.30180634, 0.09177751, 0.08608373, 0.04114688,
0. , 0. , 0. , 0. , 0. ],
[ 0.06053053, 0.80426792, 0.21038812, 0.28098004, 0.88956146,
0. , 0. , 0. , 0. , 0. ],
[ 0.17359959, 0.4629072 , 0.30100704, 0.45434713, 0.86597028,
0. , 0. , 0. , 0. , 0. ]])
This should work the same with your unicode arrays in place of the
floating point arrays here. (To make an array with all empty strings,
you can do y = np.empty((5,5), dtype='U'); y[:] = '')
-Neil
More information about the NumPy-Discussion
mailing list