矩阵删除 插入 尾部添加等操作
import numpy as np
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
p1=np.delete(matrix,1,0)
print('>>>>p1>>>>\n',p1)
>>>>p1>>>>
[[ 1 2 3 4]
[ 9 10 11 12]]
把矩阵大于或小于N的元素置M的技巧
```python
import numpy as np
x = np.array([[1,2,3],[-3,2,4],[5,-2,9]])
x
array([[ 1, 2, 3],
[-3, 2, 4],
[ 5, -2, 9]])
python
y1 = np.maximum(0,x)
y1
random.rand和random.rand和random.randint区别
import numpy as np
n = np.random.rand(3,4)
n
array([[0.5003975 , 0.8162121 , 0.45193264, 0.82332347],
[0.09752794, 0.42988813, 0.03935796, 0.8775246 ],
[0.85181714, 0.52776459, 0.14274664, 0.95744951]])
import numpy as np
x = np.random.randn(2,3)
x
python广播机制
```python
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
a=np.array([[1,2,3,6],[4,5,6,6]])
a1=a.reshape((1,2,4))
a1
numpy中的矩阵copy问题
```python
import numpy as np
x = np.array([[1,2,3],[-3,2,4],[5,-2,9]])
x
array([[ 1, 2, 3],
[-3, 2, 4],
[ 5, -2, 9]])
x1 = x.copy()
x1[x1 > 0] = 0
x1
numpy取整
import numpy as np
a=np.array([0.125,0.568,5.688])
np.round(a)
array([0., 1., 6.])
numpy基本加减和取行操作
```python
import numpy as np
A = np.arange(1, 13).reshape(6, 2)
B = np.vsplit(A, 3)
C = A.T
D = np.hsplit(C, 3)
print(A, B, C, D)
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]] [array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]])] [[ 1 3 5 7 9 11]
[ 2 4 6 8 10 12]] [array([[1, 3],
[2, 4]]), array([[5, 7],
[6, 8]]), array([[ 9, 11],
[10, 12]])]
np.zeros_like()构造全零矩阵,无需指定大小
```python
import numpy as np
x = np.array([[1,2,3],[4,5,6]])
np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
```python
np.random.choice(a, size, replace, p);np.argmax(a, axis=None, out=None)
``````python
import numpy as np
a1 = np.random.choice(7,5) # 从0~7中随机选择5个数组成一维数组
a1
array([2, 0, 5, 0, 6])
a2 = np.random.choice([0,1,2,3,4,5,6],5) # 从给定list中随机选择5个数组成一维数组
a2
array([0, 6, 1, 6, 6])
a3 = np.random.choice(np.array([0,1,2,3,4,5,6]),5) # 将list换成array数组依然可以运行,效果一致
a3
array([0, 5, 4, 2, 1])
a4 = np.random.choice([0,1,2,3,4,5,6],5,replace=False) # 上述均有重复,将replace设置为False,即可按要求没有重复的选取
a4
array([3, 0, 5, 4, 1])
a5 = np.random.choice(np.array([0,1,2,3,4,5,6]),5,p=[0.1,0.1,0.1,0.1,0.1,0.1,0.4])
a5
array([6, 3, 3, 4, 3])
import numpy as np
a = np.array([[1,1,1],[2,2,2],[0,3,6]])
a
array([[1, 1, 1],
[2, 2, 2],
[0, 3, 6]])
b1 = np.argmax(a) # 将数组a拉平,最大值索引为9(初始索引为0)
b1
8
8
b2 = np.argmax(a, axis=0) # 按列选取最大值的索引
b2
array([1, 2, 2], dtype=int64)
b3 = np.argmax(a, axis=1) # 按行选取最大值的索引
b3
array([0, 0, 2], dtype=int64)