Array operations in python (transpose, arithmetic operations)

1. Array transposition.
Array transposition can use the transpose method or the T attribute . Transpose returns a view of the original array without any copy operation.

    #reshape(shape)函数改变数组形状,参数shape是一个元组,表示数组的形状
    arr00 = np.arange(15).reshape((3,5))
    print("原始数组为:\n",arr00)
    #方法一:使用transpose()进行转置
    print("使用transpose进行转置:\n",arr00.transpose())
    #方法二:使用T属性进行转置
    print("使用T属性进行转置:\n",arr00.T)

It can be seen from the running results that the two methods can realize the transposition of the array, and the results are as follows:
Insert picture description here
2. Arithmetic operation
First, the calculation between the arrays requires the same structure of the two arrays, otherwise a ValueError error will be reported, as follows:
Insert picture description here
(1) Add and subtract
two The addition of
two arrays is equivalent to the addition of each corresponding element: the subtraction of two arrays is equivalent to the subtraction of each corresponding element. The
operations of adding 1 to each element of the arr00 array and subtracting 1 are implemented as follows:

    arr00 = np.arange(15).reshape((3,5))
    arr11 = np.ones((3,5))
    print("原始数组为:\n", arr00)
    print("原始数组为:\n", arr11)
    #数组的算术运算
    #加
    print("两个数组进行加运算:\n",arr00+arr11)
    #减
    print("两个数组进行减运算:\n", arr00 - arr11)

Running results:
Insert picture description here
(2) Constructing an array
of the same element To facilitate the demonstration of the multiplication operation, you can use the tile (A, reps) function to construct an array of the same element.
Parameter A: indicates the array to be copied.
Parameter reps: is the corresponding axis direction Number of times copied
Insert picture description here

(3)
Multiply and divide Multiply: Multiply the positions corresponding to the
two arrays Divide: Multiply the positions corresponding to the two arrays:

arr00 = np.arange(15).reshape((3,5))
arr22 = np.tile([2],(3,5))
print("两个数组进行乘运算:\n", arr00 * arr22)
print("两个数组进行除运算:\n", arr00 / arr22)

Insert picture description here
3. Array and scalar arithmetic operations
(1) Square each element in the array

print("原始数组的各个元素的平方为:\n", arr00**2)

(2) Addition and subtraction of each element in the array

print("原始数组各个元素加1为:\n", arr00+1)
print("原始数组各个元素减1为:\n", arr00 - 1)

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44801116/article/details/110294477