Matrix Operation of numpy_ndarray
Matrix Operation of ndarry
Array is a concept in programming, matrix and vector are mathematical concepts.
In computer programming, matrices can be defined in the form of arrays, and vectors can be defined in structures.
1. Vector operations: operations between arrays of the same size are applied to elements
Sample code (1):
# Vector and vector operation arr = np.array ([[1,2,3], [4,5,6]]) print ("element multiplication:") print (arr * arr) print ("matrix addition:") print (arr + arr)
Running result:
Element multiplication: [[1 49] [16 25 36]] Matrix addition: [[2 46] [8 10 12]] Vector and scalar operations: "broadcast"-broadcast scalars to each element # vector and scalar operations print (1. / arr) print (2. * arr)
Calculation result:
[[0.33333333] [0.250.2]] [[2.4.6] [8.10. 12]] the indexing of ndarray and slice one-dimensional array and the list indexing function of slicing and Python are similar.
Sample code (1):
# one-dimensional array arr1 = np.arange (10) print (arr1) print (arr1 [2:5])
Running result:
Indexing and slicing of [0 1 2 3 4 5 6 7 8 9] [2 34] multidimensional array
Arr [r1:r2, c1:c2]
Arr [1] equivalent arr [1] [1]
[:] represents the data of a dimension
Sample code (2):
# Multidimensional array arr2 = np.arange (12). Reshape (3,4) print (arr2) print (arr2 [1]) print (arr2 [0:2, 2:]) print (arr2 [:, 1:3])
Running result:
[[0 1 23] [4 567] [8 9 10 11]] [4 5 67] [2 3] [6 7]] [[1 2] [5 6] [9 10]] conditional index Boolean multidimensional array: arr [condition], condition can also be multiple conditional combinations.
Note that multiple combinations of conditions use the & | connection instead of Python's and or.
Sample code (3):
# conditional index # find out the data in data_arr after 2005 data_arr = np.random.rand (3,3) print (data_arr) year_arr = np.array ([[2000, 2001, 2000], [2005, 2002, 2009], [2001, 2003, 2010]]) is_year_after_2005 = year_arr > = 2005print (is_year_after_2005) Is_year_after_2005.dtype) filtered_arr = data_ arr [is _ year_after_2005] print (filtered_arr) # filtered_arr = data_ arr [year _ arr > = 2005] # print (filtered_arr) # multiple conditions filtered_arr = data_arr [(year_arr)