Python Numpy 的 array() 和 asarray() 函数有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14415741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:24:05  来源:igfitidea点击:

What is the difference between Numpy's array() and asarray() functions?

pythonarraysnumpy

提问by Benjamin Hodgson

What is the difference between Numpy's array()and asarray()functions? When should you use one rather than the other? They seem to generate identical output for all the inputs I can think of.

Numpyarray()asarray()函数有什么区别?什么时候应该使用一种而不是另一种?它们似乎为我能想到的所有输入生成相同的输出。

采纳答案by abarnert

Since other questions are being redirected to this one which ask about asanyarrayor other array creation routines, it's probably worth having a brief summary of what each of them does.

由于其他问题被重定向到这个询问asanyarray其他数组创建例程的问题,因此可能值得对每个问题做一个简短的总结。

The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.

区别主要在于何时返回不变的输入,而不是将新数组作为副本。

arrayoffers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:

array提供了多种选项(大多数其他功能都是围绕它的薄包装),包括确定何时复制的标志。完整的解释与文档一样长(参见Array Creation,但简而言之,这里有一些示例:

Assume ais an ndarray, and mis a matrix, and they both have a dtypeof float32:

假设andarray,并且mmatrix,他们都拥有dtypefloat32

  • np.array(a)and np.array(m)will copy both, because that's the default behavior.
  • np.array(a, copy=False)and np.array(m, copy=False)will copy mbut not a, because mis not an ndarray.
  • np.array(a, copy=False, subok=True)and np.array(m, copy=False, subok=True)will copy neither, because mis a matrix, which is a subclass of ndarray.
  • np.array(a, dtype=int, copy=False, subok=True)will copy both, because the dtypeis not compatible.
  • np.array(a)并且np.array(m)将复制两个,因为这是默认行为。
  • np.array(a, copy=False)并且np.array(m, copy=False)会复制m但不会复制a,因为m不是ndarray.
  • np.array(a, copy=False, subok=True)并且np.array(m, copy=False, subok=True)不会复制两者,因为m是 a matrix,它是 的子类ndarray
  • np.array(a, dtype=int, copy=False, subok=True)将两者都复制,因为dtype不兼容。

Most of the other functions are thin wrappers around arraythat control when copying happens:

大多数其他函数都是array在复制发生时围绕该控件的薄包装:

  • asarray: The input will be returned uncopied iff it's a compatible ndarray(copy=False).
  • asanyarray: The input will be returned uncopied iff it's a compatible ndarrayor subclass like matrix(copy=False, subok=True).
  • ascontiguousarray: The input will be returned uncopied iff it's a compatible ndarrayin contiguous C order (copy=False, order='C').
  • asfortranarray: The input will be returned uncopied iff it's a compatible ndarrayin contiguous Fortran order (copy=False, order='F').
  • require: The input will be returned uncopied iff it's compatible with the specified requirements string.
  • copy: The input is always copied.
  • fromiter: The input is treated as an iterable (so, e.g., you can construct an array from an iterator's elements, instead of an objectarray with the iterator); always copied.
  • asarray:如果输入是兼容的ndarray( copy=False) ,则输入将被未复制地返回。
  • asanyarray:如果输入是兼容的ndarray或子类,如matrix( copy=False, subok=True) ,则输入将被未复制地返回。
  • ascontiguousarray:如果输入ndarray在连续的 C 顺序中兼容( copy=False, order='C').
  • asfortranarray:如果输入ndarray在连续的 Fortran 顺序 ( copy=False, order='F') 中兼容,则输入将被未复制地返回。
  • require:如果输入与指定的要求字符串兼容,则将返回未复制的输入。
  • copy: 输入总是被复制。
  • fromiter: 输入被视为可迭代的(例如,您可以从迭代器的元素构造一个数组,而不是一个object带有迭代器的数组);一直复制。

There are also convenience functions, like asarray_chkfinite(same copying rules as asarray, but raises ValueErrorif there are any nanor infvalues), and constructors for subclasses like matrixor for special cases like record arrays, and of course the actual ndarrayconstructor (which lets you create an array directly out of strides over a buffer).

还有一些便利的功能,如asarray_chkfinite(相同复制的规则asarray,但加薪ValueError如果有任何naninf值),并像子类的构造函数matrix或特殊情况下,像记录阵列,当然实际的ndarray构造函数(它可以让你直接创建一个数组超出缓冲区的步幅)。

回答by unutbu

The definition of asarrayis:

定义asarray是:

def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

So it is like array, except it has fewer options, and copy=False. arrayhas copy=Trueby default.

所以它就像array,只是它的选项较少,而copy=Falsearraycopy=True默认。

The main difference is that array(by default) will make a copy of the object, while asarraywill not unless necessary.

主要区别在于array(默认情况下)将制作对象的副本,而asarray除非必要,否则不会。

回答by asheeshr

The differences are mentioned quite clearly in the documentation of arrayand asarray. The differences lie in the argument list and hence the action of the function depending on those parameters.

array和的文档中非常清楚地提到了这些差异asarray。区别在于参数列表,因此函数的操作取决于这些参数。

The function definitions are :

函数定义是:

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

and

numpy.asarray(a, dtype=None, order=None)

The following arguments are those that may be passed to arrayand notasarrayas mentioned in the documentation :

下面的参数是那些可以传递到arrayasarray在文件中提到:

copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

ndmin : int, optional Specifies the minimum number of dimensions that the resulting arrayshould have. Ones will be pre-pended to the shape as needed to meet this requirement.

copy : bool, optional如果为真(默认),则对象被复制。否则,只有在__array__返回副本、obj 是嵌套序列或需要副本以满足任何其他要求(dtype、顺序等)时,才会进行副本。

subok : bool,可选如果为 True,则子类将被传递,否则返回的数组将被强制为基类数组(默认)。

ndmin : int,可选 指定结果数组应具有的最小维数。将根据需要预先设置形状以满足此要求。

回答by Bobbie Wu

The difference can be demonstrated by this example:

可以通过此示例演示差异:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.arrayto modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarrayto modify A. It worked because you are modifying Aitself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    
  1. 生成矩阵

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. 使用numpy.array修改A。不起作用,因为您正在修改副本

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. 使用numpy.asarray修改A。它有效,因为你正在修改A自己

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

希望这可以帮助!

回答by vivek

Here's a simple example that can demonstrate the difference.

这是一个可以演示差异的简单示例。

The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.

主要区别在于数组会复制原始数据,使用不同的对象我们可以修改原始数组中的数据。

import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)

The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.

数组 (a) 中的内容保持不变,我们仍然可以使用另一个对象对数据执行任何操作,而无需修改原始数组中的内容。

回答by off99555

asarray(x)is like array(x, copy=False)

asarray(x)就好像 array(x, copy=False)

Use asarray(x)when you want to ensure that xwill be an array before any other operations are done. If xis already an array then no copy would be done. It would not cause a redundant performance hit.

asarray(x)当您要确保x在完成任何其他操作之前将是一个数组时使用。如果x已经是一个数组,则不会进行复制。它不会造成多余的性能损失。

Here is an example of a function that ensure xis converted into an array first.

这是一个确保x首先转换为数组的函数示例。

def mysum(x):
    return np.asarray(x).sum()