Numpyについてのメモ
- float からintへ
- 配列をランダムでシャッフル random.shuffle
- ones , zeros
- 各軸で取り出し
- 連結:np.r, np.c
- unique:配列の要素をカウントする
- random
float からintへ
>>> x = np.array([1.1, 3.5, 4.8]) >>> x.astype(np.int) array([1, 3, 4])
配列をランダムでシャッフル random.shuffle
>>> datas = np.arange(100) >>> datas array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]) >>> np.random.shuffle(datas) >>> datas array([41, 36, 80, 33, 19, 67, 10, 92, 12, 52, 42, 37, 88, 57, 5, 96, 64, 74, 86, 51, 94, 69, 30, 95, 40, 78, 0, 18, 21, 45, 99, 58, 6, 49, 3, 76, 48, 54, 15, 32, 60, 14, 17, 63, 13, 53, 38, 65, 11, 4, 97, 84, 79, 27, 7, 93, 24, 72, 2, 90, 55, 20, 91, 61, 77, 22, 29, 9, 68, 47, 35, 87, 50, 70, 98, 26, 23, 75, 83, 34, 44, 28, 25, 59, 71, 85, 62, 82, 89, 31, 43, 66, 8, 16, 39, 56, 1, 46, 73, 81])
ones , zeros
>>> np.ones((3,1)) array([[1.], [1.], [1.]])
>>> np.zeros((3,2)) array([[0., 0.], [0., 0.], [0., 0.]])
>>> np.c_[np.ones((3,1)),np.zeros((3,2))] array([[1., 0., 0.], [1., 0., 0.], [1., 0., 0.]])
各軸で取り出し
行で取り出し
>>> datas = np.array([[0,1],[2,3],[4,5]]) >>> datas[0] array([0, 1])
列で取り出し
>>> datas = np.array([[0,1],[2,3],[4,5]]) >>> datas[:,0] array([0, 2, 4])
連結:np.r, np.c
>>> import numpy as np >>> A = np.array([[1,2], [3,4]]) >>> B = np.array([[0,0], [0,0]]) >>> np.r_[A, B] array([[1, 2], [3, 4], [0, 0], [0, 0]]) >>> np.c_[A, B] array([[1, 2, 0, 0], [3, 4, 0, 0]])
unique:配列の要素をカウントする
>>> arr = [0,0,1] >>> uni, counts = np.unique(arr,return_counts=True) >>> uni array([0, 1]) >>> counts array([2, 1])
random
permutaion(並べ替え)
名前の通り、数値の並べ替えを行うメソッド。
引数が整数なら、0から引数までの整数をランダムで並べ替えたnumpy.arrayを返す
>>> np.random.permutation(10) array([8, 3, 7, 9, 1, 0, 4, 6, 2, 5])
引数が配列なら配列をランダムで並べ替えたnumpy.arrayを返す
>>> np.random.permutation([1,2,3,4,5,6]) array([4, 2, 3, 5, 6, 1]) >>> %history -p -o
- 参考文献:document