Encyclopedia of common commands numpy

In recent self-numpy, from the Internet to find a video of view, I feel a lot numpy instruction, fear not remember so unified posted for easy access.

import numpy as np Numpy import module, commonly abbreviated as np

array = np.array([[1,2,3],[2,3,4]])

numpy property

print (array) print out the array

print("number of dim:",array.ndim) Judgment arrays are a few dimensions (one-dimensional two-dimensional, and so on)

print("shape:",array.shape)Determining the shape of the array

print("size:"array.size) Determining the size of the array

Create numpy array

array = np.array([[1,2,3],[2,3,4]]Create a simple (note that there is no middle number after the next print)

array = np.array([[1,2,3],dtype=np.int)

print(array.dtype) dtype set array format, generally int, float, etc., default is 64-bit, 32-bit, if you want to change the Int32, generally speaking the number of bits smaller footprint smaller, generally 64-bit Reserved

a = np.zeros((5))

a = np.nes((5))

a = np.empty(([3,4])) 0 1 common full full full empty array

a=np.arange(10,20,2).reshape((3,4)) Generating from steps 1020 to an integer array 2 (not including the default position 20, 10 is 0), and again becomes three rows and four columns of array formats

a = np.linespace(1,10,20)Generating a line segment, line segment 20 is generated parts

numpy basic operation

a=np.array([10,20,30,40])

b=np.arange(4)Generating an array of from 0 to 3,

Conventional arithmetic, i.e., + - * / are done directly calculate the corresponding bit result, when the use of a single matrix when the power to follow the rules with Python ** trigonometric function needs to be called, for example, c = np.sin (a ). Analyzing conditions can be applied directly to the brackets, such as print (b <3). A two-dimensional matrix multiplication (linear algebra from the point of view) as follows:

c_dot=np.dot(a,b)

or

c_dot_2=a.dot(b)

Array a randomly generated, each element is a random number between 0 and 1, it is necessary to develop the shape:

a = np.random.random((2,4))

np.sum(a,axis=1)Sum, axis = 1 is to find for each column, axis = 0 are looking for in each row, each will find calculated for each row (column)

np.min(a)For the minimum

np.max(a)Seeking maximum

np.argmin(a)Index the minimum requirements

np.argmax(a)Seeking the maximum index

np.mean(a)Averaging

np.median(a)Seeking median

np.cumsum(a)It is a cumulative process, and gradually added to the list, showing each step of the accumulated

np.diff(a)Tired difference is the difference between each element and before

np.nonzero(a) To find a non-zero number and their indexes listed

np.sort(a)Sequence

np,transpose(a)Matrix reverse, and reverse the ranks of exchange

np.clip(a,3,5)Intercept, A 3 is less than all three of him, so that he 5 is greater than 5, the same intermediate

numpy Index

A=np.arange(3,15).reshape((3,4))

print (A [3]) is similar to Python, a dimension of the corresponding index is directly accessible, access to a single two-dimensional index is corresponding to the line, a single element, such as bis corresponding index is, print(A[2][1])and print(A[2,1])is the same , print(A[2,:])representing all of the second row, print(A[1,1:3])the second row from 1 to 3, i.e. the number 8 and 9

for loop:

for row in A:

print(row)Iterate Row

for column in A.T(That is, in front of the transpose):

print(column)Iterative Sequence

A.flatten() Flattened

a.ravel()  # returns the array, flattened

for item in A.flat:

print(item)Iterative project, flat is above iterator

numpy array merge

A = np.array([1,1,1])

B = np.array([2.2.2])

C = print(np.vstack((A,B))) The combined vertical stack from top to bottom

D = print(np.hstack((A,B))) Merger or so horizontal stack

!--print(A[np.newaxis,:])--A to add a dimension. ?

E = np.concatenate((A,B,B),axis=0)A plurality of array combined, axis = 0 are combined in the vertical dimension

numpy array split

A = np.arange(12).reshape((3,4))

print(np.spilt(A,2,axis=1)) The average A longitudinally divided into two parts (note that the number of columns spilt must be divisible by 2), axis = 0 is divided transversely

print(np.array_spilt(A,2,axis=1))``不等量分割

print(np.vspilt(A,3))

print(np.vspilt(A,3)) 同上面的合并

numpy array replication and deep copy (copy & deep copy)

The video speak very briefly, so here the official documents turn.

There are three cases:

# Completely replicate

Simple assignment or a copy will be created array object data.

>>> a = np.arange(12)
>>> b = a            # no new object is created
>>> b is a           # a and b are two names for the same ndarray object
True
>>> b.shape = 3,4    # changes the shape of a
>>> a.shape
(3, 4)

Python object as a variable passed by reference, so the function call does not replicate.

>>> def f(x):
...     print(id(x))
...
>>> id(a)                           # id is a unique identifier of an object
148293216
>>> f(a)
148293216

# View or shallow copy

Different objects can share the same array of data. viewMethod creates a new array object, it looks at the same data.

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

Returns an array slice view:

>>> 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

copy The method of generating 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
>>> d[0,0] = 9999
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])

# Functions and methods Overview

Here are some useful according to the method name and function NumPy arranged by category. For a complete list see Routines.

  1. Array creation

    arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r, zeros, zeros_like

  2. Change

    ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat

  3. technique

    array_split, column_stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack

  4. problem

    all, any, nonzero, where

  5. order

    argmax, argmin, argsort, max, min, ptp, searchsorted, sort

  6. operating

    choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real, sum

  7. Basic Statistics

    , mean, std, var

  8. Basic Linear Algebra

    motocross, dot, outerwear, linalg.svd, VDOT

Guess you like

Origin www.cnblogs.com/crossain/p/11223000.html