为什么此数组重塑例程在函数外部而不在函数内部起作用? [英] Why does this array-reshaping routine work outside of a function but not inside of a function?

查看:115
本文介绍了为什么此数组重塑例程在函数外部而不在函数内部起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表转换为具有指定列数的numpy数组.我可以使代码在函数外运行,如下所示:

I am trying to convert a list into a numpy array with a specified number of columns. I can get the code to work outside the function as follows:

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 do not understand my error when trying to throw the routine in a function. My attempt is as follows:

# 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 in this way because I want another function, consisting of the same inputs and a third input to loop over rows when extracting values, to call this original function for each loop over rows.

推荐答案

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,)

无需再次包装在array中;已经是一个了

No need to wrap again in array; it already is one:

In [405]: np.array(ls)
Out[405]: array([   1.,   12.,   23.,   34.,   45.,   56.,   67.,   78.,   89.,  100.])

resize就地运行.它不返回任何内容(或无)

resize operates 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)

使用此resize,您无需更改元素的数量,因此reshape同样适用.

With this resize you aren't changing the number of elements, so reshape would 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返回一个值,而ls保持不变. -1是方便的空手,避免了//除法.

reshape in either method or function form returns a value, leaving ls unchanged. The -1 is a handy short hand, avoiding the // division.

这是整形的就地版本:

In [415]: ls.shape=(-1,2)

reshape需要相同的元素总数. resize允许您更改元素的数量,必要时可以截断或重复值.与resize相比,我们更频繁地使用reshape. repeattile也比resize更常见.

reshape requires the same total number of elements. resize allows you to change the number of elements, truncating or repeating values if needed. We use reshape much more often then resize. repeat and tile are also more common than resize.

这篇关于为什么此数组重塑例程在函数外部而不在函数内部起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆