Why does this array rebuilding routine work outside of a function but not inside a function?
I am trying to convert a list to a numpy array with a specified number of columns. I can get the code to work outside of the function like this:
import numpy as np
ls = np.linspace(1,100,100) # Data Sample
ls = np.array(ls) # list --> array
# resize | outside function
ls.resize(ls.shape[0]//2,2)
print(ls)
>> [[ 1. 2.]
[ 3. 4.]
.
.
.
[ 97. 98.]
[ 99. 100.]]
I don't understand my mistake when trying to cast a subroutine in a function. My attempt is this:
# resize | inside function
def shapeshift(mylist, num_col):
num_col = int(num_col)
return mylist.resize(mylist.shape[0]//num_col,num_col)
ls = shapeshift(ls,2)
print(ls)
>> None
I want to define the original function this way, because I want another function, consisting of the same inputs and a third input, to iterate over the rows while fetching values, call that original function for each row-by-row loop.
source to share
In [402]: ls = np.linspace(1,100,10)
In [403]: ls
Out[403]: array([ 1., 12., 23., 34., 45., 56., 67., 78., 89., 100.])
In [404]: ls.shape
Out[404]: (10,)
No need to wrap again array
; he is already alone:
In [405]: np.array(ls)
Out[405]: array([ 1., 12., 23., 34., 45., 56., 67., 78., 89., 100.])
resize
works in place. It returns nothing (or None)
In [406]: ls.resize(ls.shape[0]//2,2)
In [407]: ls
Out[407]:
array([[ 1., 12.],
[ 23., 34.],
[ 45., 56.],
[ 67., 78.],
[ 89., 100.]])
In [408]: ls.shape
Out[408]: (5, 2)
With this, resize
you are not changing the number of items, so it reshape
will work just as well.
In [409]: ls = np.linspace(1,100,10)
In [410]: ls.reshape(-1,2)
Out[410]:
array([[ 1., 12.],
[ 23., 34.],
[ 45., 56.],
[ 67., 78.],
[ 89., 100.]])
reshape
in the form of a method or function, returns the value, leaving it ls
unchanged. -1
- comfortable short hand, avoiding separation //
.
This is the inplace replacement version:
In [415]: ls.shape=(-1,2)
reshape
requires the same total number of items. resize
allows you to change the cardinality, truncate or repeat values as needed. We use reshape
much more often than resize
. repeat
and are tile
also more common than resize
.
source to share
The method .resize
works in place and returns None
. It also refuses to work at all if there are other names referring to the same array. You can use the form of a function that creates a new array and is not moody:
def shapeshift(mylist, num_col):
num_col = int(num_col)
return np.resize(mylist, (mylist.size//num_col,num_col))
source to share