numpy library summary

numpy study

0x01: n-dimensional array object ndaarray
store the same type of multidimensional array elements

0x02: numpy Data type
Value Type dtype numpy fact an instance of the object, and corresponds to a unique character, including np.bool_, np.int32, np.float32, and the like.
Word definition structured data types:

import numpy as np
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) 
print(a)

0x03: attribute array
ndarray.ndim: rank, i.e. the number of dimensions of the shaft or the number of
dimensions of the array ndarray.shape, for the matrix, n-rows and m columns
the total number of array elements ndarray.size, corresponding to the n * .shape m value
NumPy reshape also provides functions to adjust the size of the array.

a = np.array([[1,2,3],[4,5,6]]) 
b = a.reshape(3,2)  
print (b)

0x04: Creating an array
numpy.empty way to create a predetermined shape (shape), data type (DTYPE) uninitialized array:

x = np.empty([3,2], dtype = int) 
print (x)

numpy.zeros / ones to create the specified size of the array, the array elements are 0/1 to fill:

x = np.zeros(5) 
print(x)

x = np.ones(5) 
print(x)

0x05: create an array from an existing array
umpy.asarray similar numpy.array, but numpy.asarray only three parameters, numpy.array less than two.

numpy.asarray(a, dtype = None, order = None)
a   任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组
dtype   数据类型,可选
order   可选,有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

0x06: Create a range of values from the array
numpy package using arange function to create and return a numerical range ndarray objects, functions in the following format:

numpy.arange(start, stop, step, dtype)

numpy.linspace function to create a one-dimensional array, the array is composed of an arithmetic sequence, the following format:

np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

umpy.logspace function is used to create a geometric sequence. Format is as follows:

np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

0x07: sections and index
content ndarray object can be accessed and modified through an index or slices, like slices of operations in Python list.
ndarray array based on 0 - n subscript for the index, the object slice by slice built-in functions, and set the start, stop, and step parameters, a new array cut from the original array.

a = np.arange(10)
s = slice(2,7,2)   # 从索引 2 开始到索引 7 停止,间隔为2
print (a[s])

Colon: explanation: If you place only one parameter, such as [2], returns a single element corresponding to the index. If [2:], indicating that all items will be retrieved later from the beginning of the index. Item: [72], then extracting two indexes (not including the stop index) between If two parameters, such as.

import numpy as np
a = np.arange(10)
print(a[2:])

Array after a row is extracted: a multidimensional array index extraction method described above is equally applicable

a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(a)
# 从某个索引处开始切割
print('从数组索引 a[1:] 处开始切割')
print(a[1:])

0x08: advanced indexing
integer array index: mapping two elements of the array in a position to determine
the following examples acquisition array (0,0), (1,1) and (2,0) at the position of the element.

x = np.array([[1,  2],  [3,  4],  [5,  6]]) 
y = x[[0,1,2],  [0,1,0]]  
print (y)

0x09: numpy broadcast
broadcast (Broadcast) is numpy different shapes (Shape) array of numerical embodiment, an array of arithmetic operations typically performed on the corresponding elements.
If the two arrays a and b are the same shape, i.e., meet a.shape == b.shape, then the result is a * b a and b are multiplied by the corresponding bit array. This requires the same dimensions and the same length in each dimension.

a = np.array([1,2,3,4]) 
b = np.array([10,20,30,40]) 
c = a * b 
print (c)

输出结果为:
[ 10  40  90 160]

When calculating the shape of two arrays are different, numpy triggered automatically broadcast mechanism. Such as:

a = np.array([[ 0, 0, 0],
       [10,10,10],
       [20,20,20],
       [30,30,30]])
b = np.array([1,2,3])
print(a + b)

输出结果为:
[[ 1  2  3]
 [11 12 13]
 [21 22 23]
 [31 32 33]]

4x3 two-dimensional array with a length of 3 by adding one-dimensional array, the array b is equivalent to 4 times on a two-dimensional repeated recalculation:

0x10: iterative array
NumPy iterator object numpy.nditer provides a flexible access to one or more of the elements of an array.
Iterator most basic tasks can be done to access array elements.
Next we use arange () function creates a 2X3 array and use it to iterate nditer.
Examples

a = np.arange(6).reshape(2,3)
print ('原始数组是:')
print (a)
print ('\n')
print ('迭代输出元素:')
for x in np.nditer(a):
    print (x, end=", " )
print ('\n')

Control traversal order:
for X in np.nditer (A, Order = 'F.'): The Fortran Order, i.e., a priority order is a column;
for X in np.nditer (the aT, Order = 'C'): Order C, that is line order of priority;

Modify the value of elements in the array
nditer object has another optional parameters op_flags. By default, nditer array traversal iteration will depend be subject to read-only (read-only), at the same time through the array in order to achieve modifications worth array elements must be specified read-write or write-only mode.

Examples

import numpy as np
 
a = np.arange(0,60,5) 
a = a.reshape(3,4)  
print ('原始数组是:')
print (a)
print ('\n')
for x in np.nditer(a, op_flags=['readwrite']): 
    x[...]=2*x 
print ('修改后的数组是:')
print (a)

输出结果为:

原始数组是:
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]


修改后的数组是:
[[  0  10  20  30]
 [ 40  50  60  70]
 [ 80  90 100 110]]

0x11: array operations
comprising Numpy several functions for processing in the array, can be roughly divided into the following categories: modifying the shape of the array, the array inverted, modified array dimensions, connector array, a striped array, additions, and deletions array element

numpy.reshape 函数可以在不改变数据的条件下修改形状The following form: numpy.reshape (arr, newshape, order = 'C')

numpy.ndarray.flat 是一个数组元素迭代器Examples are as follows:

import numpy as np
a = np.arange(9).reshape(3,3) 
print ('原始数组:')
for row in a:
    print (row)
 
# 对数组中每个元素都进行处理,可以使用flat属性,该属性是一个数组元素迭代器:
print ('迭代后的数组:')
for element in a.flat:
    print (element)

输出结果如下:
原始数组:
[0 1 2]
[3 4 5]
[6 7 8]
迭代后的数组:
0
1
2
3
4
5
6
7
8

Different methods previously nditer is flat, nditer numpy is a method of, and the default is read-only objects, and method is a method flat array of objects.

numpy.ravel() 展平的数组元素, The order is usually "C style", returns an array of view (view, somewhat similar to C / C ++ references mean reference), the changes will affect the original array. To be understood as simply converted to a multi-dimensional array is an array
This function receives two parameters:
numpy.ravel (A, Order = 'C')

numpy.transpose 函数用于对换数组的维度, Column line change, the following format:
numpy.transpose (ARR, axes)
Parameters:
ARR: the array to operate
axes: list of integers, corresponding to the dimensions, all dimensions are usually swapped.

numpy.ndarray.T 类似 numpy.transpose: Column change row

numpy.swapaxes 函数用于交换数组的两个轴,格式如下:
numpy.swapaxes (ARR, Axis1, Axis2)
ARR: input array
axis1: a first axis corresponding to integer
axis2: an integer corresponding to the second axis

Connection array

| Function | Description |
|: - |: |
| CONCATENATE | serial array along the connection axis prior |
| Stack | Add new series along the array axes |
| hstack | horizontally stacked array sequence (column direction) |
| vStack | stacking sequence in a vertical array (row direction) |

Striped array

| Function | | array and operating |
|: |: |
| Split | one array is divided into a plurality of sub-arrays
| hsplit | dividing an array level of a plurality of sub-arrays (columns)
| vsplit | dividing an array of vertical multi- sub-array (rows)

Adding and removing array elements

| Function | elements and descriptions
|: |: |
| a resize | return to a predetermined shape new array
| the append | add value to the end of the array
| INSERT | axis along a specified value into a specified index before
| Delete | a deleted axis sub-arrays, and returns the new array after deleting
| unique | Find unique elements in the array

0x12: numpy bit computing
function NumPy "bitwise_" the beginning of the bit operation function.
NumPy bit operation includes the following functions:

| Function | Description
|: |: |
| bitwise_and | array element performs bitwise AND
| bitwise_or | bit array elements or perform operations
| Rate History For Converting | bitwise
-bit binary representation leftward | | left_shift
| right_shift | to Right-bit binary representation of movement

0x13: numpy String Functions
The following functions are used for the quantization dtype numpy.string_ string or array operable to perform the numpy.unicode_. They Python built-in library functions standard string based. These functions are defined in the character array class (numpy.char) in.

| Function | Description
|: |
| the Add () | of two-by-string element array are connected, mapping between elements
| Multiply () | Returns the string by connecting multiple elements, to a multi-string is returned times
| Center () | centered string, and filled with the specified characters in the left and right.
| capitalize () | first letter of the string converted to uppercase
| title () | Converts the first letter of each word of a string to uppercase
| lower () | for each element of the array is converted to lowercase. It calls for each element str.lower.
| upper () | function on each element of the array is converted to uppercase. It calls for each element str.upper.
| Split () | by dividing the specified delimiter string, and returns an array. By default, a space for the separator.
| The splitlines () | function to the newline character as a delimiter to separate the string, and returns an array.
| Strip () | specific characters removal elements at the beginning or end of
| the Join () | elements in the array are connected by designating a delimiter
| Replace () | all sub new string in the replacement string
| decode () | array element in turn calls str.decode
| encode () | array element in turn calls str.encode

0x14: numpy math
NumPy contains a large variety of mathematical functions, including trigonometric function, an arithmetic operation function, a plurality of processing functions and the like.

三角函数:NumPy 提供了标准的三角函数: Sin (), cos (), tan ().

numpy.around() 函数返回指定数字的四舍五入值.
numpy.around (a, decimals)
Parameters:
A: Array
decimals: rounding decimal places. The default value is 0. If negative, rounded to an integer of the decimal place of the left

numpy.floor() 返回数字的下舍整数。

numpy.ceil() 返回数字的上入整数。

0x15: numpy arithmetic functions
NumPy contain simple arithmetic functions加减乘除: add(),subtract(),multiply() 和 divide()。

print ('两个数组相加:')
print (np.add(a,b))

print ('两个数组相减:')
print (np.subtract(a,b))

print ('两个数组相乘:')
print (np.multiply(a,b))

print ('两个数组相除:')
print (np.divide(a,b))

numpy.reciprocal() 函数返回参数逐元素的倒数. As the countdown 1/4 4/1.

a = np.array([0.25,  1.33,  1,  100])  
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 reciprocal 函数:')
print (np.reciprocal(a))

numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂

numpy.mod() 计算输入数组中相应元素的相除后的余数。 函数 numpy.remainder() 也产生相同的结果。Parameters are two arrays, the first element of the array do dividend, return an array consisting of a remainder

0x16: numpy statistical functions
NumPy provides a number of statistical functions, is used to find the smallest element from an array, the largest element, percentile standard deviation and variance:

numpy.amin () array elements used to calculate the minimum value along a specified axis. 1 represents the minimum row, 0 represents a minimum space in the array represents the smallest
maximum numpy.amax () for calculating the elements of the array along a given axis.

a = np.array([[3,7,5],[8,4,3],[2,4,9]])  
print (a)

print (np.amin(a,1))

print (np.amin(a,0))

print (np.amax(a))

print (np.amax(a, axis =  0))

mpy.ptp () function computes the difference between the array elements in the maximum and minimum (maximum - minimum)

print ('调用 ptp() 函数:')
print (np.ptp(a))

print ('沿轴 1 调用 ptp() 函数:')
print (np.ptp(a, axis =  1))

print ('沿轴 0 调用 ptp() 函数:')
print (np.ptp(a, axis =  0))

numpy.median () Median (median) a function for calculating the array of elements: rows, columns, or entire array computing

numpy.mean () function returns the arithmetic mean of the elements of the array: in rows, columns, or entire array computing

numpy.average () function is a weighted average of elements in the array is calculated according to the weight of the respective weights given in another array.

0x17: numpy sorting, filtering function condition
sorting algorithm: 'quicksort' (quicksort) 'mergesort' (merge sort) 'heapsort' (heap sort)
numpy.sort() 函数returns a copy of the sorted input array. Function following format:
numpy.sort (A, axis, kind, Order)
Parameters:
A: array to be sorted
axis: the axis along which the sorted array, the array will be deployed if not, the final sorted along the axis, axis = 0 column ordered, axis = 1 row ordered
kind: default 'quicksort' (quicksort)
Order: If the array contains a field, the field is to sort

numpy.argsort () function returns the value of an array of small to large index values.

numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。

numpy.where() 函数返回输入数组中满足给定条件的元素的索引。

numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。

0x18: numpy matrix library (Matrix)
matlib.empty () function returns a new matrix, syntax is:
numpy.matlib.empty (Shape, DTYPE, Order)
Parameters:
Shape: integer defining a new matrix shape or a whole-number group
Dtype: Alternatively, data types
order: C (line-sequential priority) or F (column priority order)

import numpy.matlib 
import numpy as np
print (np.matlib.empty((2,2)))
  • numpy.matlib.zeros () function creates a zero-fill matrix.
  • numpy.matlib.ones () function creates a matrix to fill 1.
  • numpy.matlib.rand () function creates a matrix of given size, the data is randomly populated.
  • numpy.matlib.identity () function returns a matrix of given size. Is a square matrix, the elements on the diagonal from left to bottom right (called the main diagonal) are 1, except that all zero.

numpy.matlib.eye () function returns a matrix of diagonal elements of 1, is zero elsewhere.
numpy.matlib.eye (n, M, k, dtype)
Parameters:
n-: Returns the number of rows in the matrix
M: Returns the number of columns of the matrix, the default is n-
K: index diagonal
DTYPE: Data Type
Example:

import numpy.matlib 
import numpy as np 
print (np.matlib.eye(n =  3, M =  4, k =  0, dtype =  float))

0x19: numpy linear algebra
NumPy provides linear algebra library linalg, which library contains all the functions required linear algebra, you can see the following description:

| Function | Description
|: |
| DOT | dot product of two arrays, i.e., by multiplying the corresponding element.
| VDOT | dot product of two vectors
| || Inner inner product of two arrays
| gcc - internal | matrix product of two arrays
| determinant | determinant of an array
| Solve | linear matrix equation
| INV | multiplicative inverse matrix calculation matrix

numpy 和 matplotlib

from matplotlib import pyqlot as plt

plt.title graphic title
plt.xlable x-axis title
plt.ylable y axis title
plt.plot (x, y) drawing
plt.show () it is showing
plt.hist

subplot() 函数Allows you to draw different things in the same figure, that can put a piece of canvas is divided into several sub-canvas, in the sub-canvas painting something different. How many points can canvas child. Depending on the high and wide sub-set canvas. Function takes three parameters, the first high child canvas, canvas second sub wide, the third is the number of sub-canvas. Child canvas actual height and width you set the height and width of the countdown, set high added 4, a width of 2, then the child's actual height and width of the canvas is the whole canvas 1/4 1/2, the height and width settings the smaller, the more the number of sub-division canvas. All sub canvas height or width of not more than 1

bar () function to generate a bar chart: two number of array elements must be equal to the incoming, with drawing function, instead of the above plt.plot

numpy.histogram () function is a graphical representation of the frequency distribution data. Equal to the size of the rectangular horizontal interval corresponding to the class, called bin, corresponding to the frequency variable height.
numpy.histogram () function and the input array bin as two parameters. bin array of contiguous elements of each bin is used as a boundary.

Guess you like

Origin www.cnblogs.com/liangxiyang/p/11594093.html