数据挖掘工具numpy(六)Numpy数组间运算

一,数组与数的计算

# 数组与数进行计算是,数与数组的每一个数据分别进行计算。
# 这是numpy的广播机制造成的,加减乘除的值被广播到所有元素上面。
import numpy as np

temp = np.array([[1,2,3,4],[3,4,5,6],[7,8,9,0]],dtype='i4')
temp1 = temp + 3
temp2 = temp * 3

print(temp,temp.shape,temp.ndim)
print(temp1,temp1.shape,temp1.ndim)
print(temp2,temp2.shape,temp2.ndim)

# -------------output---------------------
[[1 2 3 4]
 [3 4 5 6]
 [7 8 9 0]] (3, 4) 2
[[ 4  5  6  7]
 [ 6  7  8  9]
 [10 11 12  3]] (3, 4) 2
[[ 3  6  9 12]
 [ 9 12 15 18]
 [21 24 27  0]] (3, 4) 2

二,数组与数组进行计算(广播机制)

1,当数组和数组具有相同的维度时,才可以进行计算。

广播原则
如果两个数组的后缘维度(从末尾开始计算起的维度)的轴长度相符或其中一方的长度为1,
则认为他们是广播兼容的,广播会在缺失和(或)长度为1的维度上进行。

2,当两个数组的shape(形状)相同时,可以直接对应位进行加减乘除的计算。
import numpy as np
temp = np.array([[1,2,3,4],[3,4,5,6],[7,8,9,0]],dtype='i4')
temp1 = temp
temp2 = temp / temp1
print(temp2,temp2.shape,temp2.ndim)

RuntimeWarning: invalid value encountered in true_divide
[[ 1.  1.  1.  1.]
  temp2 = temp / temp1
 [ 1.  1.  1.  1.]
 [ 1.  1.  1. nan]] (3, 4) 2
3,当数组和数组有相同的维度数字时的计算

两个数组从末尾开始,数字如果相匹配(数字相等,或者为1)则可以进行计算

import numpy as np

temp = np.arange(15)
temp1 = temp.reshape(3,1,5)
temp2 = np.arange(4).reshape(1,4,1)
temp3 = temp1 * temp2
print(temp1)
print(temp2)
print(temp3,temp3.shape,temp3.ndim)


# -------------output---------------------
[[[ 0  1  2  3  4]]

 [[ 5  6  7  8  9]]

 [[10 11 12 13 14]]]
 ------------------------------
[[[0]
  [1]
  [2]
  [3]]]
  ------------------------------
[[[ 0  0  0  0  0]
  [ 0  1  2  3  4]-
  [ 0  2  4  6  8]
  [ 0  3  6  9 12]]

 [[ 0  0  0  0  0]
  [ 5  6  7  8  9]
  [10 12 14 16 18]
  [15 18 21 24 27]]

 [[ 0  0  0  0  0]
  [10 11 12 13 14]
  [20 22 24 26 28]
  [30 33 36 39 42]]] (3, 4, 5) 3

三,矩阵计算

1,什么是矩阵

矩阵,matrix,和array的区别矩阵必须是2维的,但是array可以是多维的。

2,特点

矩阵计算必须是2维的。(M行, N列) x (N行, L列) = (M行, L列)

3,numpy转化为矩阵实例
import numpy as np

temp= np.arange(1,11,dtype=np.int32).reshape(2,5)
print(type(temp))
temp = np.mat(temp)
print(temp,type(temp))

# -------------output---------------------
<class 'numpy.ndarray'>
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]] <class 'numpy.matrix'>

4,矩阵计算实例

import numpy as np

temp1= np.arange(1,11,dtype=np.int32).reshape(5,2)
temp1 = np.mat(temp1)
print(temp1,type(temp1))

temp2 = np.mat([[1, 2],[3, 4]])
print(temp2,type(temp2))

# total = temp1 * temp2
total = np.dot(temp1,temp2)
print(total)

# -------------output---------------------
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]] <class 'numpy.matrix'>
[[1 2]
 [3 4]] <class 'numpy.matrix'>
[[ 7 10]
 [15 22]
 [23 34]
 [31 46]
 [39 58]]

猜你喜欢

转载自blog.csdn.net/TFATS/article/details/106274824