NumPy: From existing data

np.array v.s. np.asarray

  • 二者接口
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

由上,知np.asarray是通过np.array实现的,但两者的copy默认值不同了。

  • 测试
In [1]: a
Out[1]: array([1, 2, 3])

In [2]: np.array(a)
Out[2]: array([1, 2, 3])

In [3]: np.asarray(a)
Out[3]: array([1, 2, 3])

In [4]: np.array(a) is a
Out[4]: False

In [5]: np.asarray(a) is a
Out[5]: True

=================================

In [6]: np.array(a)[1] = 10

In [7]: a
Out[7]: array([1, 2, 3])

In [8]: np.asarray(a)[1] = 10

In [9]: a
Out[9]: array([ 1, 10,  3])

可见,np.array(a)创建了一个a的副本,但np.asarray(a)却没有。

  • read more
    numpy.asarray官方文档说明

np.asarray v.s. np.asanyarray

  • 定义
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)
def asanyarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order, subok=True)

可见,二者的区别就是subok这参数项。在np.asarray中使用的是np.array中默认的,即subok=False;而np.asanyarray中的是subok=True

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).
  • 测试
In [1]: a = np.matrix([1,2])

In [2]: a
Out[2]: matrix([[1, 2]])

In [3]: np.asarray(a) is a
Out[3]: False

In [4]: np.asanyarray(a) is a
Out[4]: True

======================================

In [5]: b = np.asarray(a)

In [6]: b
Out[6]: array([[1, 2]])

In [7]: c = np.asanyarray(a)

In [8]: c
Out[8]: matrix([[1, 2]])

matrixnarray的一个子类。如文档所说的,

 If a is a subclass of ndarray, a base class ndarray is returned.

对于np.asarray,返回的是一个基类,即narray,而不是matrix

Convert the input to an ndarray, but pass ndarray subclasses through.
If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.

故对于np.asanyarray返回的仍是matrix类型的。

  • read more
    numpy.asanyarray官方文档说明

np.copy

  • define
def copy(a, order='K'):
    return array(a, order=order, copy=True)
np.copy(a)  is equivalent to np.array(a, copy=True)
  • test
In [1]: a = np.array([1, 1, 1])

In [2]: b = a

In [3]: c = a.copy()

==================================================

In [6]: c[1] = 3

In [7]: c
Out[7]: array([1, 3, 1])

In [8]: a
Out[8]: array([1, 1, 1])

In [9]: b[1] = 3

In [10]: a
Out[10]: array([1, 3, 1])

==================================================

In [12]: a is b
Out[12]: True

In [13]: a is c
Out[13]: False

  • read more
    numpy 官方文档

np.asmatrix

  • define
def asmatrix(data, dtype=None):
    return matrix(data, dtype=dtype, copy=False)
  • test
In [14]: a = np.array([1, 1, 1])

In [16]: b = np.asmatrix(a)

In [17]: b
Out[17]: matrix([[1, 1, 1]])

In [18]: a[1] = 2

In [19]: b
Out[19]: matrix([[1, 2, 1]])

In [20]: a is b
Out[20]: False
  • read more
    NumPy 官方文档

你可能感兴趣的:(NumPy: From existing data)