[Numpy-discussion] Array resize question

Scott Sinclair scott.sinclair.za@gmail....
Wed Jun 17 02:03:59 CDT 2009


> 2009/6/16 Cristi Constantin <darkgl0w@yahoo.com>
>
> 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

The resize method of ndarray is currently broken when the 'order'
keyword is specified, which is why you get the SystemError

http://projects.scipy.org/numpy/ticket/840

It's also worth knowing that the resize function and the ndarray
resize method both behave a little differently. Compare:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html

and

http://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html

Basically, the data in your original array is inserted into the new
array in the one dimensional order that it's stored in memory and any
remaining space is filled with repeats of the data (resize function)
or packed with zero's (resize array method).

# resize function
>>> import numpy as np
>>> a = np.array([[1, 2],[3, 4]])
>>> print a
[[1 2]
 [3 4]]
>>> print np.resize(a, (3,3))
[[1, 2, 3],
 [4, 1, 2],
 [3, 4, 1]])

#resize array method
>>> b = np.array([[1, 2],[3, 4]])
>>> print b
[[1 2]
 [3 4]]
>>> b.resize((3,3))
>>> print b
[[1 2 3]
 [4 0 0]
 [0 0 0]]

Neil's response gives you what you want in this case.

Cheers,
Scott


More information about the Numpy-discussion mailing list