Summary of important knowledge points of numpy

data type

dtype is used to customize the type. i1, i2, i4, i8 denote int8, int16, int32, int64. S20 String Representing a Specific Length

dtype([('key','value type'), ('key','value type'), ('value type'),... )

import numpy as np

# Define type
dt = np.dtype([("age","i4")])
Student = np.dtype([("name","S10"),("age", np.int32),("marks", "f4")])

# Create variables of custom type
a = np.array([[1,2],[3,4],[5,6]], dtype=dt)
b = np.array([1,3,5], 			dtype=dt)
c = np.array([("tom", 20, 99.9),("tim", 22, 98.9),("karl", 22, 100)], dtype=Student)


print(dt)	# [('age', '<i4')]
print(a)	
print(b)	# [(1,) (3,) (5,)]
print(c)	# [(b'tom', 20,  99.9) (b'tim', 22,  98.9) (b'karl', 22, 100. )]

print(a["age"])		# [[1 2] [3 4] [5 6]]
print(c["name"])	# [b'tom' b'tim' b'karl']

Array ndarray

  • zeros(shape),ones(shape),empty(shape), np.full(shape=(3,4), fill_value=4)
  • Eye (N, M = None, k=0, dtype = < class'float'>): Diagonal matrix, when k > 0, represents the first line on the upper right, and k=0 represents the unit matrix.

Constructive function of ndarray

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

  • dtype: Specifies the type of array elements
  • copy: Does an object need to be copied
  • order: Create the style of the array, C is the row direction, F is the column direction, A is the arbitrary direction.
  • subok: Returns an array that is identical to the class type
  • ndmin: Specify the minimum dimension
a = np.array([1,2,3,4,5,6])
b = np.array([[1,2,3],[4,5,6]])
c = np.array([1,2,3,4,5,6], ndmin=2)
d = np.array([1,2,3,4,5,6], ndmin=3)	
e = np.array([[1,2,3],[4,5,6]],ndmin=3)

print(a)	# [1 2 3 4 5 6]
print(b)	# [[1 2 3] [4 5 6]] 
print(c)	# [[1 2 3 4 5 6]]
print(d)	# [[[1 2 3 4 5 6]]]
print(e)	# [[[1 2 3] [4 5 6]]]

print(d[0,0,0])		# Three-dimensional arrays are one-dimensional arrays as the third dimension.
print(e[0,0,0])
print(e[0,1,0])		# Three-dimensional arrays treat two-dimensional arrays as dimensions 2 and 3

ndarray attribute

attribute Explain
ndim Rank, number of axes, number of dimensions
shape Dimensions of arrays, n rows and m columns for Matrices
size Total number, n*m
dtype Element type
itemsize The size of each element in bytes

np.shape and np.reshape()

a = np.array([[1,2,3],[4,5,6]])
print(a.shape)		# (2,3)	
a.shape = (3,2) 	# Equivalent to a.reshape(3,2)
print(a)			# (3,2)

dimension

a = np.arange(24)
b = a.reshape(2,3,4)
print(a)
print(b)

###
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]

### Two 3*4 arrays (2*3*4)
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

Create empty arrays (elements are random values)

np.empty(shape, dtype = float, order = 'C'/'F')

np.empty((2,2), dtype=int)
np.empty(2,dtype=int)

###
[[1701540705, 1635131492],
 [1936029036,  537528878]]

[0, 1073741824]

Create a full-0 array

np.zeros(shape, dtype=float, order='C'/'F')

np.zeros(5, dtype=int)
np.zeros((5,), dtype=int)
np.zeros((2,2), dtype=[('x', int),('y', int)])

###
array([0, 0, 0, 0, 0])
array([0, 0, 0, 0, 0])
array([[(0, 0), (0, 0)],
       [(0, 0), (0, 0)]], dtype=[('x', '<i4'), ('y', '<i4')])

Create a full 1 array:

numpy.ones(shape, dtype = None, order = 'C')

np.ones(5)
np.ones((2,2))

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

Create arrays using arange (returning ndarray directly, range() returning list objects)

numpy.arange(start=0, stop, step=1, dtype) # If there is only one parameter, it means [0, stop]

  • start Initial value (0)
  • stop Termination value [start, stop)
  • step step
  • dtype data type

Sequence np.linspace()

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

  • start: start value
  • stop: Termination value
  • num: Sample size of equal step (default is 50)
  • endpoint: ture contains stop value, and vice versa (default is True)
  • retstep: If True, the spacing is displayed in the generated array, and not vice versa.
  • dtype: data type of ndarray
np.linspace(0,10,5)
np.linspace(1,10,5)
np.linspace(0,10,5,endpoint=False)

Equal ratio sequence np.logspace()

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

  • start : The starting value is:base ** start
  • stop : The termination value of the sequence is:base ** stop.
  • num : Sample size of equal step(The default is 50)
  • endpoint : ture Then include stop Value, and vice versa(The default is True)
  • base : Logarithm log The base number (default is 10)
  • dtype : ndarray Data type
np.logspace(1,10,10,base=2)
np.logspace(0,9,10,base=2)
np.logspace(0,9,10)
np.logspace(0,9,10,base=10)

###
array([   2.,    4.,    8.,   16.,   32.,   64.,  128.,  256.,  512.,  1024.])
array([  1.,   2.,   4.,   8.,  16.,  32.,  64., 128., 256., 512.])
array([1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09])  ## 1.0e+00 saves 0 after decimal point
array([1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07, 1.e+08, 1.e+09])

asarray and array

When initializing arrays with ndarray, if array retains a copy, asarray does not use a copy. [Reference]

numpy.asarray(a, dtype = None, order = None)

array = np.eye(3,3)
array1 = np.array(array)
array2 = np.asarray(array)
array[0] = 2			# Change the value of array

print(array1)
print(array2)

###
array([[1., 0., 0.],		# The value of array1 remains unchanged. It's a copy.
       [0., 1., 0.],
       [0., 0., 1.]])
array([[2., 2., 2.],		# The value of array2 also changed, not a copy.
       [0., 1., 0.],
       [0., 0., 1.]])

Summary

  • eye(n): Create a unit matrix
  • Empty (shape, dtype = float, order ='C'/'F'): Create an uninitialized array
  • zeros(shape, dtype=float, order='C'/'F'): Create a full-0 array
  • ones(shape, dtype=float, order='C'/'F'): Create an array of all 1
  • full(shape, num): Create an array of shapes and fill it with num
  • ndarray arange(start=0, stop, step=1, dtype): an array of equals. Arnge (stop) denotes [0, stop]; arange (start, stop) denotes [start, stop]; and arange (start, stop, step) denotes step size.

Indexes

slice(start, stop, step) # Returns the slice type
//Or array [start: stop: step] # [start, stop)

a = np.arange(1,11)
s = slice(0,10,2)
print(a[s])
print(a[0:11:2])

###
[1 3 5 7 9]
a = np.arange(start=1,stop=11, step=1)
a		# [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]
a[2:5]	# [3, 4, 5]
a[0:]	# [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10]
a[:2]	# [1, 2]

Multidimensional arrays:

a = np.array([[1,2,3],[3,4,5],[4,5,6],[7,8,9]])  
print(a) 			# [[1 2 3] [3 4 5] [4 5 6] [7 8 9]]
print (a[...,1])  	# Column 2 Elements [24,58]
print (a[1,...])    # Line 2 element [345]
print (a[...,1:])   # Column 2 and all remaining elements [[23] [45] [56] [89]]

operation

+-*/% ** n: Addition, subtraction, multiplication, division, redundancy and n-th power of the corresponding position elements of a matrix

  • Matrix multiplication: a.dot(b)
  • Matrix transpose: a.transpose() or a.T
  • Matrix inversion: np.linalg.pinv(a) or a.I

np.dot(a,b), a.dot(b), matrix multiplication

Common Functions

a.max(axis=0) a.max(axis=1) a.argmax(axis=1): the maximum value of each column (maximum value in line direction), the maximum value of each row (approximate value in column direction), and the coordinates of the maximum value

  • sum() summation, mean(), var() variance, std() standard deviation: use similar to max

  • np.random.uniform(a,b) random decimal

  • np.tile(a,(1,2)): Repeat once on the line and twice on the column.

  • arr.argsort(): Returns a sequence number from small to large with a return value of python's list

  • sorted(iterable, cmp=None, key=None, reverse=False): Sort all Iterable objects. Retain the original object and return the new object. reverse=False denotes from small to large

  • list.sort(cmp=None, key=None, reverse=False): Sort lists, directly operate on the original list

  • The itemgetter function provided by the operator module is used to obtain which dimensions of the object's data

a = [5,8,2,7,21]
b = operator.itemgetter(0)
b(a)

b = operator.itemgetter(1,0)
b(a)

###
5
(8,5)
  • Updating Modified Modules Using Reoad (KNN)
import importlib
importlib.reload(KNN)

Tags: Attribute Python

Posted on Tue, 10 Sep 2019 04:11:10 -0700 by brad.techguy