3_1Numpy之ndarray

https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

NumPy’s main object is the homogeneous(同构的) multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called axes. The number of axes is rank.

For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3. In the example pictured below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

[[ 1., 0., 0.],
[ 0., 1., 2.]]

1 ndarray类

在numpy中,array是ndarray的别称。
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality.

1.1 The more important attributes of an ndarray

The more important attributes of an ndarray object are:

ndarray.ndim

the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape

the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension.

ndarray.size

the total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtype

an object describing the type of the elements in the array.

ndarray.itemsize

the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.

2 Array Creation

import numpy as np
a = np.array([2,3,4])
a
array([2, 3, 4])
a.dtype
dtype('int32')
b = np.array([1.2, 3.5, 5.1])
b.dtype
dtype('float64')
np.array([(1.5,2,3), (4,5,6)])
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])
np.array( [ [1,2], [3,4] ], dtype=complex )
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j]])
np.zeros( (3,4) )
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

np.zeros_like(a, dtype=None, order='K', subok=True)
Return an array of zeros with the same shape and type as a given array.

x = np.arange(6).reshape((2,3))
np.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]])
np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specified
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]], dtype=int16)
np.empty( (2,3) )                                 # uninitialized, output may vary
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])
#创建单位矩阵
np.eye(4)

array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])

To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.

np.arange( start=10, stop=30, step=5 )#步长为5
array([10, 15, 20, 25])
np.arange( 0, 2, 0.3 )                 # it accepts float arguments
array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])

When arange is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step:

np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  ])
from numpy import pi
x = np.linspace( 0, 2*pi, 100 ) 
x
array([0.        , 0.06346652, 0.12693304, 0.19039955, 0.25386607,
       0.31733259, 0.38079911, 0.44426563, 0.50773215, 0.57119866,
       0.63466518, 0.6981317 , 0.76159822, 0.82506474, 0.88853126,
       0.95199777, 1.01546429, 1.07893081, 1.14239733, 1.20586385,
       1.26933037, 1.33279688, 1.3962634 , 1.45972992, 1.52319644,
       1.58666296, 1.65012947, 1.71359599, 1.77706251, 1.84052903,
       1.90399555, 1.96746207, 2.03092858, 2.0943951 , 2.15786162,
       2.22132814, 2.28479466, 2.34826118, 2.41172769, 2.47519421,
       2.53866073, 2.60212725, 2.66559377, 2.72906028, 2.7925268 ,
       2.85599332, 2.91945984, 2.98292636, 3.04639288, 3.10985939,
       3.17332591, 3.23679243, 3.30025895, 3.36372547, 3.42719199,
       3.4906585 , 3.55412502, 3.61759154, 3.68105806, 3.74452458,
       3.8079911 , 3.87145761, 3.93492413, 3.99839065, 4.06185717,
       4.12532369, 4.1887902 , 4.25225672, 4.31572324, 4.37918976,
       4.44265628, 4.5061228 , 4.56958931, 4.63305583, 4.69652235,
       4.75998887, 4.82345539, 4.88692191, 4.95038842, 5.01385494,
       5.07732146, 5.14078798, 5.2042545 , 5.26772102, 5.33118753,
       5.39465405, 5.45812057, 5.52158709, 5.58505361, 5.64852012,
       5.71198664, 5.77545316, 5.83891968, 5.9023862 , 5.96585272,
       6.02931923, 6.09278575, 6.15625227, 6.21971879, 6.28318531])
np.sin(x)
array([ 0.00000000e+00,  6.34239197e-02,  1.26592454e-01,  1.89251244e-01,
        2.51147987e-01,  3.12033446e-01,  3.71662456e-01,  4.29794912e-01,
        4.86196736e-01,  5.40640817e-01,  5.92907929e-01,  6.42787610e-01,
        6.90079011e-01,  7.34591709e-01,  7.76146464e-01,  8.14575952e-01,
        8.49725430e-01,  8.81453363e-01,  9.09631995e-01,  9.34147860e-01,
        9.54902241e-01,  9.71811568e-01,  9.84807753e-01,  9.93838464e-01,
        9.98867339e-01,  9.99874128e-01,  9.96854776e-01,  9.89821442e-01,
        9.78802446e-01,  9.63842159e-01,  9.45000819e-01,  9.22354294e-01,
        8.95993774e-01,  8.66025404e-01,  8.32569855e-01,  7.95761841e-01,
        7.55749574e-01,  7.12694171e-01,  6.66769001e-01,  6.18158986e-01,
        5.67059864e-01,  5.13677392e-01,  4.58226522e-01,  4.00930535e-01,
        3.42020143e-01,  2.81732557e-01,  2.20310533e-01,  1.58001396e-01,
        9.50560433e-02,  3.17279335e-02, -3.17279335e-02, -9.50560433e-02,
       -1.58001396e-01, -2.20310533e-01, -2.81732557e-01, -3.42020143e-01,
       -4.00930535e-01, -4.58226522e-01, -5.13677392e-01, -5.67059864e-01,
       -6.18158986e-01, -6.66769001e-01, -7.12694171e-01, -7.55749574e-01,
       -7.95761841e-01, -8.32569855e-01, -8.66025404e-01, -8.95993774e-01,
       -9.22354294e-01, -9.45000819e-01, -9.63842159e-01, -9.78802446e-01,
       -9.89821442e-01, -9.96854776e-01, -9.99874128e-01, -9.98867339e-01,
       -9.93838464e-01, -9.84807753e-01, -9.71811568e-01, -9.54902241e-01,
       -9.34147860e-01, -9.09631995e-01, -8.81453363e-01, -8.49725430e-01,
       -8.14575952e-01, -7.76146464e-01, -7.34591709e-01, -6.90079011e-01,
       -6.42787610e-01, -5.92907929e-01, -5.40640817e-01, -4.86196736e-01,
       -4.29794912e-01, -3.71662456e-01, -3.12033446e-01, -2.51147987e-01,
       -1.89251244e-01, -1.26592454e-01, -6.34239197e-02, -2.44929360e-16])

3 Printing Arrays

When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:

the last axis is printed from left to right,
the second-to-last is printed from top to bottom,
the rest are also printed from top to bottom, with each slice separated from the next by an empty line.
One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices.

4 Basic Operations

Arithmetic operators on arrays apply elementwise(作用于每个元素). A new array is created and filled with the result.

a = np.array( [20,30,40,50] )
b = np.arange( 4 )
a-b
array([20, 29, 38, 47])
b**2
array([0, 1, 4, 9], dtype=int32)
10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
a<35
array([ True,  True, False, False])

Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the dot function or method。

A = np.array( [[1,1], [0,1]] )
B = np.array( [[2,0],[3,4]] )
A*B                         # elementwise product
array([[2, 0],
       [0, 4]])
A.dot(B)                    # matrix product
array([[5, 4],
       [3, 4]])
np.dot(A, B)                # another matrix product
array([[5, 4],
       [3, 4]])

Some operations, such as += and *=, act in place to modify an existing array rather than create a new one

5 Iterating

Iterating over multidimensional arrays is done with respect to the first axis:

def f(x,y):
    return 10*x+y
b = np.fromfunction(f,(5,4),dtype=int)
b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])
for row in b:
    print(row)
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]

However, if one wants to perform an operation on each element in the array, one can use the flat attribute which is an iterator over all the elements of the array:

for element in b.flat:
    print(element)
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43

6 Shape Manipulation

6.1 Changing the shape of an array

The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array

The order of the elements in the array resulting from ravel() is normally “C-style”, that is, the rightmost index “changes the fastest”, so the element after a[0,0] is a[0,1]. If the array is reshaped to some other shape, again the array is treated as “C-style”. NumPy normally creates arrays stored in this order, so ravel() will usually not need to copy its argument, but if the array was made by taking slices of another array or created with unusual options, it may need to be copied.

a = np.floor(10*np.random.random((3,4)))
a
array([[2., 7., 7., 9.],
       [6., 7., 2., 0.],
       [6., 4., 4., 8.]])
a.flat

a.ravel()  # returns the array, flattened
array([2., 7., 7., 9., 6., 7., 2., 0., 6., 4., 4., 8.])
a.reshape(6,2)  # returns the array with a modified shape
array([[2., 7.],
       [7., 9.],
       [6., 7.],
       [2., 0.],
       [6., 4.],
       [4., 8.]])

If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated:

a.reshape(3,-1)
array([[2., 7., 7., 9.],
       [6., 7., 2., 0.],
       [6., 4., 4., 8.]])
a.T
array([[2., 6., 6.],
       [7., 7., 4.],
       [7., 2., 4.],
       [9., 0., 8.]])
a.shape
(3, 4)

The reshape function returns its argument with a modified shape, the ndarray.resize method modifies the array itself:

a.resize((2,6))
a
array([[2., 7., 7., 9., 6., 7.],
       [2., 0., 6., 4., 4., 8.]])

Stacking together different arrays

Several arrays can be stacked together along different axes:

a = np.floor(10*np.random.random((2,2)))
a
array([[1., 8.],
       [2., 2.]])
b = np.floor(10*np.random.random((2,2)))
b
array([[3., 8.],
       [2., 4.]])
np.vstack((a,b))
array([[1., 8.],
       [2., 2.],
       [3., 8.],
       [2., 4.]])
np.hstack((a,b))
array([[1., 8., 3., 8.],
       [2., 2., 2., 4.]])

Splitting one array into several smaller ones

Using hsplit, you can split an array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur.

vsplit splits along the vertical axis, and array_split allows one to specify along which axis to split.

a = np.floor(10*np.random.random((2,12)))
a
array([[8., 4., 7., 2., 3., 6., 3., 6., 9., 0., 2., 6.],
       [7., 8., 8., 7., 3., 6., 9., 1., 9., 7., 4., 1.]])
np.hsplit(a,3)   # Split a into 3
[array([[8., 4., 7., 2.],
        [7., 8., 8., 7.]]), array([[3., 6., 3., 6.],
        [3., 6., 9., 1.]]), array([[9., 0., 2., 6.],
        [9., 7., 4., 1.]])]

Copies and Views

When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases:

No Copy at All(不发生拷贝)

Simple assignments make no copy of array objects or of their data.

a = np.arange(12)
b = a #no new object is created, a and b are two names for the same ndarray object
id(a)
96769088
id(b)
96769088

Python passes mutable objects as references, so function calls make no copy.

View or Shallow Copy

Different array objects can share the same data. The view method creates a new array object that looks at the same data.

c = a.view()
id(c)
96770048
c is a
False
c.base is a                        # c is a view of the data owned by a
True
c.base
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
c.shape = 2,6                      # a's shape doesn't change
a.shape
(12,)
c[0,4] = 1234                      # a's data changes
a
array([   0,    1,    2,    3, 1234,    5,    6,    7,    8,    9,   10,
         11])

Slicing an array returns a view of it:

a.shape = 3,4
s = a[ : , 1:3]     # spaces added for clarity; could also be written "s = a[:,1:3]"
s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])

Deep Copy

The copy method makes a complete copy of the array and its data.

d = a.copy()                          # a new array object with new data is created
d is a
False
d.base is a                           # d doesn't share anything with a
False

你可能感兴趣的:(3_1Numpy之ndarray)