>>>import numpy as np
随机数:
设置随机数种子:
>>>np.random.seed(66)
>>>a=np.random.randint(0,10,size=(4,5))
array([[4, 7, 3, 5, 3],
[0, 7, 6, 0, 2],
[2, 2, 6, 0, 8],
[8, 9, 9, 8, 2]])
将多维数组打平为一维数组:
>>>a.ravel()
array([4, 7, 3, 5, 3, 0, 7, 6, 0, 2, 2, 2, 6, 0, 8, 8, 9, 9, 8, 2])
>>>np.max(a)
9
>>>np.argmax(a)
16
该值为打平以后一维数组的下标,对应的原数组下标:
>>>np.unravel_index(np.argmax(a),a.shape)
(3, 1)
指定某个轴计算最大值的下标:
>>>np.argmax(a,axis=1)
array([1, 1, 4, 1])
挑选出对应的最大值:
>>>a[np.arange(a.shape[0]),np.argmax(a,axis=1)]
array([7, 7, 8, 9])
按某个轴排序
axis不指定时,默认为最后一个轴
>>>np.sort(a,axis=0)
array([[0, 2, 3, 0, 2],
[2, 7, 6, 0, 2],
[4, 7, 6, 5, 3],
[8, 9, 9, 8, 8]])
全局排序:
将axis设置为None
>>>np.sort(a,axis=None)
array([0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9])
获取排序后的下标:
>>> np.argsort(a,axis=0)
array([[1, 2, 0, 1, 1],
[2, 0, 1, 2, 3],
[0, 1, 2, 0, 0],
[3, 3, 3, 3, 2]])
>>> np.argsort(a,axis=None)
array([13, 8, 5, 9, 11, 10, 19, 4, 2, 0, 3, 7, 12, 1, 6, 18, 14,
15, 16, 17])
参考: