1. 程式人生 > >Numpy:排序及返回索引、多重複制、兩個矩陣對應元素取最小值、隨機選擇元素

Numpy:排序及返回索引、多重複制、兩個矩陣對應元素取最小值、隨機選擇元素

1.排序: sort()

# 方法一:
import numpy as np
a = np.array([[4,3,5,],[1,2,1]])
print (a)
b = np.sort(a, axis=1) # 對a按每行中元素從小到大排序
print (b)
# 輸出 [[4 3 5]
 [1 2 1]]
[[3 4 5]
 [1 1 2]]

# 方法二:
import numpy as np
a = np.array([[4,3,5,],[1,2,1]])
print (a)
a.sort(axis=1)
print (a)
# 輸出 [[4 3 5]
 [1 2 1]]
[[3 4 5]
 [1 1 2]]

# 方法三:
import numpy as np
a = np.array([4, 3, 1, 2])
b = np.argsort(a) # 求a從小到大排序的座標
print (b)
print (a[b]) # 按求出來的座標順序排序
# 輸出 [2 3 1 0]
[1 2 3 4]
2.按行或按列找到最大值的索引:argmax()
import numpy as np
data = np.sin(np.arange(20)).reshape(5, 4)
print (data)
ind = data.argmax(axis=0) # 按列得到每一列中最大元素的索引,axis=1為按行
print (ind)
data_max = data[ind, range(data.shape[1])] # 將最大值取出來
print (data_max)
# 輸出 [[ 0.          0.84147098  0.90929743  0.14112001]
 [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
 [ 0.98935825  0.41211849 -0.54402111 -0.99999021]
 [-0.53657292  0.42016704  0.99060736  0.65028784]
 [-0.28790332 -0.96139749 -0.75098725  0.14987721]]
[2 0 3 1]
[ 0.98935825  0.84147098  0.99060736  0.6569866 ]

print data.max(axis=0) #也可以直接取最大值
# 輸出 [ 0.98935825  0.84147098  0.99060736  0.6569866 ]
3.多重複制:tile()
import numpy as np
a = np.array([5, 10, 15])
print(a)
print('---')
b = np.tile(a, (4, 1)) # 引數(4, 1)為按行復制4倍,按列複製1倍
print(b)
# 輸出 [ 5 10 15]
---
[[ 5 10 15]
 [ 5 10 15]
 [ 5 10 15]
 [ 5 10 15]]

c = np.tile(a, (2, 3)) # 引數(2, 3)為按行復制2倍,按列複製3倍
print(c)
# 輸出 [[ 5 10 15  5 10 15  5 10 15]
 [ 5 10 15  5 10 15  5 10 15]]

4.兩個矩陣對應元素取最小值:minimum()

import numpy as np

a = array([[21,-12,11],[1,-3,5],[3,4,5]])
b = array([[11,12,13],[2,3,4],[3,4,5]])

c = minimum(a,b)

>>> c 
array([[ 11, -12,  11],
       [  1,  -3,   4],
       [  3,   4,   5]])

5.使用Python random模組的choice方法隨機選擇某個元素

foo = ['a', 'b', 'c', 'd', 'e']
from random import choice
print choice(foo)