NumPy的np有什么区别?数组和np.asarray?什么时候我应该使用其中一种而不是另一种?它们似乎产生了相同的输出。
当前回答
asarray的定义是:
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
它很像array,只是选项更少,copy=False。array默认copy=True。
主要的区别是,array(默认情况下)将创建对象的副本,而asarray除非必要,否则不会。
其他回答
这种差异可以通过下面的例子来证明:
Generate a matrix. >>> A = numpy.matrix(numpy.ones((3, 3))) >>> A matrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) Use numpy.array to 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.]]) Use numpy.asarray to modify A. It worked because you are modifying A itself. >>> numpy.asarray(A)[2] = 2 >>> A matrix([[ 1., 1., 1.], [ 1., 1., 1.], [ 2., 2., 2.]])
这里有一个简单的例子可以说明这种区别。
主要区别是数组会复制原始数据,而使用不同的对象我们可以修改原始数组中的数据。
import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)
数组(a)中的内容保持不变,并且仍然可以使用另一个对象对数据执行任何操作,而无需修改原始数组中的内容。
在array和asarray的文档中清楚地提到了它们的区别。区别在于参数列表,因此函数的操作取决于这些形参。
函数定义如下:
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)
and
numpy.asarray(a, dtype=None, order=None)
以下参数可以传递给array,而不是文档中提到的asarray:
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 array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
asarray的定义是:
def asarray(a, dtype=None, order=None):
return array(a, dtype, copy=False, order=order)
它很像array,只是选项更少,copy=False。array默认copy=True。
主要的区别是,array(默认情况下)将创建对象的副本,而asarray除非必要,否则不会。
asarray(x)类似于array(x, copy=False)
当你想要确保x在任何其他操作完成之前是一个数组时,使用asarray(x)。如果x已经是一个数组,则不会进行复制。它不会导致冗余的性能损失。
下面是一个函数的例子,它确保x首先被转换成一个数组。
def mysum(x):
return np.asarray(x).sum()