numpy方法的应用

时间:2018-12-03 12:43:28

标签: python numpy numpy-ndarray

我对如何将numpy方法应用于nd-array感到困惑。例如:

import numpy as np    
a = np.array([[1,2,2],[5,2,3]])
b = a.transpose()
a.sort()

这里,transpose()方法未将任何内容更改为a,而是返回a的转置版本,而sort()方法正在对a进行排序并返回NoneType。任何人都知道为什么会这样,以及这种不同功能的目的是什么?

2 个答案:

答案 0 :(得分:1)

Because numpy authors decided that some methods will be in place and some won't. Why? I don't know if anyone but them can answer that question.

'in-place' operations have the potential to be faster, especially when dealing with large arrays, as there is no need to re-allocate and copy the entire array, see answers to this question

BTW, most if not all arr methods have a static version that returns a new array. For example, arr.sort has a static version numpy.sort(arr) which will accept an array and return a new, sorted array (much like the global sorted function and list.sort()).

答案 1 :(得分:0)

在Python类(OOP)中,可以使用就地操作(修改self或其属性)的方法,并且如果有的话,比返回新对象的方法更常见。对于dictlist之类的内置类也是如此。

例如,在numpy中,我们经常推荐使用list append方法来构建新数组:

In [296]: alist = []
In [297]: for i in range(3):
     ...:     alist.append(i)
     ...:     
In [298]: alist
Out[298]: [0, 1, 2]

这很常见,我们可以很容易地将其写为列表理解:

In [299]: [i for i in range(3)]
Out[299]: [0, 1, 2]

alist.sort就地操作,sorted(alist)返回新列表。

numpy中,返回新数组的方法更为常见。实际上sort是我能想到的唯一就地方法。以及对shapearr.shape=(...)的直接修改。

许多基本的numpy操作返回一个view。与源共享数据内存,但是数组对象包装是新的。实际上,即使索引元素也会返回一个新对象。

因此,当您最终需要检查文档时,通常可以假定numpy函数或方法返回一个新对象,而不是就地操作。

更常见的是,用户对与方法同名的numpy函数感到困惑。在大多数情况下,该函数确保参数为数组,然后将操作委派给其方法。另外请记住,在Python中,运算符会转换为方法调用-+__add__[index]__getitem__()等。+=是一种放置操作。