Numpy Basics - array properties, array creation, and multiple indexes

Numpy Basics (I)

Array properties

The dimension of NumPy array is called rank. Rank is the number of axes, that is, the dimension of the array.

In NumPy, each linear array is called an axis, that is, dimensions. For example, a two-dimensional array is equivalent to two one-dimensional arrays, in which each element in the first one-dimensional array is a one-dimensional array. Therefore, a one-dimensional array is the axis in NumPy. The first axis is equivalent to the underlying array, and the second axis is the array in the underlying array. The number of axes, the rank, is the dimension of the array.

Many times you can declare axis. axis=0, indicating operation along axis 0, i.e. operation on each column; axis=1 indicates the operation along the first axis, that is, the operation is performed on each line.

attributeexplain
ndarray.ndimRank is the number of axes or dimensions
ndarray.shapeThe dimension of the array. For a matrix, n rows and m columns
ndarray.sizeThe total number of array elements, equivalent to Value of n*m in shape
ndarray.dtypeThe element type of the ndarray object
ndarray.itemsizeThe size, in bytes, of each element in the ndarray object
ndarray.flagsMemory information of the ndarray object
ndarray.realThe real part of the ndarray element
ndarray.imagImaginary part of ndarray element
ndarray.dataThe buffer containing the actual array elements usually does not need to use this attribute because the elements are generally obtained through the index of the array.

Create array

#uninitialized
numpy.empty(shape, dtype = float, order = 'C')
#Initialize to 0
numpy.zeros(shape, dtype = float, order = 'C')
#Initialize to 1
numpy.ones(shape, dtype = None, order = 'C')
parameterdescribe
shapeArray shape
dtypeData type, optional
orderThere are "C" and "F" options, representing row priority and column priority respectively, and the order of storage elements in computer memory.

Create an array from a numeric range

numpy.arange(start, stop, step, dtype)
#Start value, end value, step size, returned data type
#Generate an array of 0 ~ 5
x = np.arrange(5)
#numpy. The linspace function is used to create a one-dimensional array, which is composed of an arithmetic sequence
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
#num number of samples not generated (equal step size guaranteed) endpoint is fasle, and stop is not included in the sequence
#When retstep is true, the spacing will be displayed in the generated array
#numpy. The logspace function is used to create an equal ratio sequence
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
#Base is the base of log
a = np.logspace(0,9,10,base=2)
print (a)
#[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]

Indexes

a = np.arange(10)
s = slice(2, 7, 2)  #From index 2 to index 7, the step is 2
ic(a[s])
ic(a[2:7:2])#Three parameters start, stop and step can be separated by colons
ic(a[2:])#Represents all elements after 2
x = np.array([[1, 2], [3, 4], [5, 6]])
#Gets the element at position (0,0) (1,1) (2,0)
y = x[[0, 1, 2], [0, 1, 0]]
#Get results
[1, 4, 5]
x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print("Array is:", x)
print('\n')
# index = np.array([0, 0, 3, 3], [0, 2, 0, 2]) cannot be written like this
ic(x[[0, 0, 3, 3], [0, 2, 0, 2]]) #Generate a list
rows = np.array([[0, 0], [3, 3]])
cols = np.array([[0, 2], [0, 2]])
ic(x[rows, cols]) #Generate a matrix with 2 rows and 2 columns
#result
 x[[0, 0, 3, 3], [0, 2, 0, 2]]: array([ 0,  2,  9, 11])
 x[rows, cols]: array([[ 0,  2],
                          [ 9, 11]])
a = np.array([[1,2,3], [4,5,6],[7,8,9]])
ic(a[1:3, 1:3])
ic(a[1:3, [1, 2]])  #Note that 1:3 has the same function as [1, 2]
ic(a[:, 1:])
ic(a[..., 1:])  #... And: similar in function
#The results are as follows:

#ic| a[1:3, 1:3]: array([[5, 6],

#                        [8, 9]])

#ic| a[1:3, [1, 2]]: array([[5, 6],

#                           [8, 9]])

#ic| a[:, 1:]: array([[2, 3],

#                     [5, 6],

#                     [8, 9]])

#ic| a[..., 1:]: array([[2, 3],

#                       [5, 6],

#                       [8, 9]])

Boolean index (filter to get a specific value)

x = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
ic(x)
ic(x[x > 5])
#ic| x: array([[ 0,  1,  2],
#              [ 3,  4,  5],
#              [ 6,  7,  8],
#              [ 9, 10, 11]])
#ic| x[x > 5]: array([ 6,  7,  8,  9, 10, 11])
#Using negation operator~
a = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
ic(a[~np.isnan(a)])
#array([1., 2., 3., 4., 5.])

Fancy index

The integer array is used for indexing, and each value is taken as the following table of an axis of the target array,

x = np.arange(32).reshape((8, 4))
y = np.arange(8)
index = [4, 3, 2, 1]
ic(x)
ic(y)
ic(x[index])#A one-dimensional index of a two-dimensional array returns the contents of each row
ic(y[index])#The one-dimensional index of the one-dimensional array returns the corresponding element
#x[index]: array([[16, 17, 18, 19],
#                     [12, 13, 14, 15],
#                     [ 8,  9, 10, 11],
#                     [ 4,  5,  6,  7]])
#y[index]: array([4, 3, 2, 1])

NP. Is required to pass in multiple index arrays ix_

x=np.arange(32).reshape((8,4))
print (x[np.ix_([1,5,7,2],[0,3,1,2])])
#[[ 4  7  5  6]
#[20 23 21 22]
#[28 31 29 30]
#[ 8 11  9 10]]

Keywords: Python linear algebra

Added by zsxdcfv21 on Tue, 04 Jan 2022 13:16:57 +0200