LoginSignup
1
0

More than 3 years have passed since last update.

Numpyの基本操作をJupyter Labで書いてみた。

Last updated at Posted at 2020-04-14

この記事はかめ(@usdatascientist)さんのブログ(https://datawokagaku.com/python_for_ds_summary/ ) に書かれているNumpyの基本操作を実際にJupyter Labを用いてコーディングしてみた、という記事です。

NumPyの基本操作まとめ

Array

import numpy as np #numpyをnpとしてインポート
np.array([1,2,3,4]) #arrayのリスト
array([1, 2, 3, 4])
python_list = (1,2,3,4) #Pythonのリスト
python_list
(1, 2, 3, 4)
np.array([[1,2,3], [4,5,6],[7,8,9]]) #arrayの入れ子のリスト
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
[[1,2,3], [4,5,6],[7,8,9]] #Pythonの入れ子のリスト
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Arrayの計算

arr1 = np.array([[1,2,3], [4,5,6],[7,8,9]])
arr2 = np.array([[1,2,3], [4,5,6],[7,8,9]])
arr1
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
arr2
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
arr1 + arr2
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])
arr1 - arr2
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
arr1 * arr2
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])
arr1 / arr2
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
#arrayの足りない要素は[1,2,3]で自動的に補完される。(Broadcasting)
arr3= np.array([[1,2,3]])
arr4 = np.array([[1,2,3], [4,5,6],[7,8,9]])
arr3 + arr4 
array([[ 2,  4,  6],
       [ 5,  7,  9],
       [ 8, 10, 12]])
arr3 - arr4
array([[ 0,  0,  0],
       [-3, -3, -3],
       [-6, -6, -6]])
arr = np.array([[1,2,3], [4,5,6],[7,8,9]])
#arrayの行列のサイズを調べる
arr.shape 
(3, 3)

Indexing

indexは0から始まり、0-1番目の値まで取ってくることができる。

ndarray = np.array([[1,2], [3,4],[5,6]])
ndarray
array([[1, 2],
       [3, 4],
       [5, 6]])
ndarray[1][0]
3
ndarray[1,0]
3

Slicing

slicingは[N:M]のとき「N以上M未満」の要素を取ってくる。

arr = np.array([[1,2,3,4], [2,4,6,4], [3,5,7,4], [3,5,7,4]])
arr
array([[1, 2, 3, 4],
       [2, 4, 6, 4],
       [3, 5, 7, 4],
       [3, 5, 7, 4]])
arr[0:4, 2:4]
array([[3, 4],
       [6, 4],
       [7, 4],
       [7, 4]])
arr[:,2:] #全ての行の2列以降の要素を全て取ってくる。
array([[3, 4],
       [6, 4],
       [7, 4],
       [7, 4]])
arr = np.array([1,2,3,4,2,4,6,4,5,7,4,5,7,4])
arr[1:6:2] #2つ飛びでslicing
array([2, 4, 4])

様々なArray

np.arange[(start,)stop(,step)]

np.arange(0,5,2) #[start, stop, step] #0~5を2で区切った値のリスト
array([0, 2, 4])
np.arange(5) # start stepは省略可能。省略した場合デフォルトでそれぞれ0と1が入る。
array([0, 1, 2, 3, 4])
np.arange(0,5,0.1) #stepは0.1刻みも可能
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
       1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
       2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8,
       3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9])

np.linspace(start, stop, num=50)

np.linspace(1, 2, 20) #1~2を20等分する
array([1.        , 1.05263158, 1.10526316, 1.15789474, 1.21052632,
       1.26315789, 1.31578947, 1.36842105, 1.42105263, 1.47368421,
       1.52631579, 1.57894737, 1.63157895, 1.68421053, 1.73684211,
       1.78947368, 1.84210526, 1.89473684, 1.94736842, 2.        ])

.copy()

arr_copy = arr.copy() 
arr_copy
array([0, 1, 2, 3, 4])
ndarray = np.arange(0, 5)
ndarray_copy = ndarray.copy()
print('original array is {}'.format(id(arr)))
print('copied array is {}'.format(id(arr))) #copyしたものはコピー元とは別のオブジェクト
original array is 140571396284208
copied array is 140571396284208
ndarray[:] = 100
print('original array:\n', ndarray)    #copyしないと元のarrayが更新される
print('copied array:\n', ndarray_copy) #copyすると元のarrayが更新されない
original array:
 [100 100 100 100 100]
copied array:
 [0 1 2 3 4]
def add_world(hello):
    hello += ' world'
    return hello

h_str = 'hello'
h_list = ['h', 'e', 'l', 'l', 'o']
output_str = add_world(h_str)
output_list = add_world(h_list)

print('output_str: {}'.format(output_str)) #Stringは値渡しなので直接変更する
print('output_list: {}'.format(output_list)) #listは参照渡しなので直接変更しない

print('h_str: {}'.format(h_str))
print('h_list: {}'.format(h_list))
output_str: hello world
output_list: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
h_str: hello
h_list: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
def change_hundred(array):

    array[0] = 100 #copyしないと元のarrayが更新される
    return array

def change_hundred_copy(array):

    array_copy = array.copy() #copyすると元のarrayが更新されない
    array_copy[0] = 100
    return array_copy

array_1 = np.arange(0, 4)
array_2 = np.arange(0,4)

output_array = change_hundred(array_1)
output_array_copy = change_hundred_copy(array_2)

print('original_array_1/n', array_1)
print('original_array2/n', array_2)
original_array_1/n [100   1   2   3]
original_array2/n [0 1 2 3]

np.zeros(shape)

shape = (2,3,5) #零行列
zeros = np.zeros(shape)
print(zeros)
[[[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]

 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]

np.ones(shape)

shape = (2,3,5)
ones_array_1 = np.ones(shape)
ones_array_2 = np.ones(4)

print(ones_array_1)
print(ones_array_2)
[[[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

 [[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]]
[1. 1. 1. 1.]

np.eye(N)

np.eye(3) #N * Nの単位行列。対角成分が全て1となる。
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

np.random.rand()

random_float = np.random.rand() # 0~1からランダムな数を返す。
random_1d = np.random.rand(3)
random_2d = np.random.rand(3, 4)

print('random_float:{}'.format(random_float))
print('random_1d:{}'.format(random_1d))
print('random_2d:{}'.format(random_2d))
random_float:0.48703321814513356/n
random_1d:[0.27824053 0.60682459 0.22001138]
random_2d:[[0.52285782 0.87272074 0.03123286 0.7921472 ]
 [0.80209903 0.26478273 0.91139303 0.63077037]
 [0.72151924 0.91234378 0.69355857 0.9969298 ]]

np.random.randn()

random_float = np.random.randn() #標準正規分布0〜1から値が返される。
random_1d = np.random.randn(3)
random_2d = np.random.randn(3, 4)

print('random_float:{}'.format(random_float))
print('random_1d:{}'.format(random_1d))
print('random_2d:{}'.format(random_2d))
random_float:-0.013248078417389888
random_1d:[-1.11606544 -0.24693187  0.17212059]
random_2d:[[-0.85896581  0.53993487  0.09458454  1.3505381 ]
 [-1.83510873  0.09966918 -0.22293729  0.58218476]
 [ 0.37403933  0.83349568  0.73407002 -0.32979339]]

np.random.randint(low[,high][,size])

np.random.randint(10, 50, size=(2,4,3)) #low以上high未満のintegerからランダムに、指定したsizeのndarrayを返す。 今回は2次元の4行3列。
array([[[30, 14, 11],
        [33, 24, 48],
        [15, 43, 41],
        [18, 26, 49]],

       [[18, 22, 16],
        [15, 10, 43],
        [43, 48, 10],
        [42, 29, 10]]])

.reshape(shape)

array = np.arange(0, 10)
print('array:{}'.format(array))
new_shape = (2, 5)
reshaped_array = array.reshape(new_shape)

print('reshaped array:{}'.format(reshaped_array))
print("reshaped array's is {}".format(reshaped_array.reshape))
print('original array is NOT changed:{}'.format(array))
array:[0 1 2 3 4 5 6 7 8 9]
reshaped array:[[0 1 2 3 4]
 [5 6 7 8 9]]
reshaped array's is <built-in method reshape of numpy.ndarray object at 0x7fd9420d8030>
original array is NOT changed:[0 1 2 3 4 5 6 7 8 9]

要素の統計量を求める

normal_dist_mat = np.random.randn(5,5)
print(normal_dist_mat) 
[[-1.51861663 -2.09873943 -0.99761607  0.95395101 -0.04577882]
 [-0.81944941  0.54339984  0.45265577 -2.56369775 -1.8300719 ]
 [ 0.63372482 -0.35763135  0.31683655  1.44185989 -1.2110421 ]
 [-1.56200024  1.17061544  1.35721624 -0.46023814  0.3496441 ]
 [ 1.09102475 -0.47551934 -0.75747612  0.34564251  1.62400795]]

.max() 最大値

print('max is')
print(normal_dist_mat.max()) 
max is
1.6240079549859363

.argmax() 最大値のindexを求める。

print('argmax is')
print(normal_dist_mat.argmax()) 
argmax is
24

.flatten()[] index=9に格納された値を一列にする。

normal_dist_mat.flatten()[9] 
-1.83007190063398

.min() 最小値

print('min is')
print(normal_dist_mat.min()) 
min is
-2.5636977453276137

.argmin() 最小値のindexを求める。

print('argmin is')
print(normal_dist_mat.argmin()) 
argmax is
8

.mean() 平均値

print('mean is') 
print(normal_dist_mat.mean())
mean is
-0.1766919366579146

np.median(ndarray) 中央値

print('median is')
print(np.median(normal_dist_mat)) 
median is
-0.04577882007895756

.std() 標準偏差

print('standard deviation is')
print(normal_dist_mat.std())
standard deviation is
1.1634432893009636
print(normal_dist_mat.std())  #上記の関数は全てnp.関数名(ndarray)で呼ぶことも可能
1.1634432893009636
print(normal_dist_mat) #特定の行,列での統計量を求めたい場合は引数axisを指定。
print('axis=0 > {}'.format(normal_dist_mat.max(axis=0))) #axis=0を指定すると各列の統計量,
print('axis=1 > {}'.format(normal_dist_mat.max(axis=1))) #axis=1を指定すると各行の統計量を返す。
[[-1.51861663 -2.09873943 -0.99761607  0.95395101 -0.04577882]
 [-0.81944941  0.54339984  0.45265577 -2.56369775 -1.8300719 ]
 [ 0.63372482 -0.35763135  0.31683655  1.44185989 -1.2110421 ]
 [-1.56200024  1.17061544  1.35721624 -0.46023814  0.3496441 ]
 [ 1.09102475 -0.47551934 -0.75747612  0.34564251  1.62400795]]
axis=0 > [1.09102475 1.17061544 1.35721624 1.44185989 1.62400795]
axis=1 > [0.95395101 0.54339984 1.44185989 1.35721624 1.62400795]

数学で使う関数

np.exp(ndarray) 

ndarray = np.linspace(-3,3,10)
expndarray = np.exp(ndarray)
print(ndarray)
print(expndarray)
[-3.         -2.33333333 -1.66666667 -1.         -0.33333333  0.33333333
  1.          1.66666667  2.33333333  3.        ]
[ 0.04978707  0.09697197  0.1888756   0.36787944  0.71653131  1.39561243
  2.71828183  5.29449005 10.3122585  20.08553692]

np.log(nd.array)

ndarray = np.linspace(-3,3,10)
logndarray = np.log(ndarray)
print(ndarray)
print(logndarray) #負の値は対数を取れないのでnan。
[-3.         -2.33333333 -1.66666667 -1.         -0.33333333  0.33333333
  1.          1.66666667  2.33333333  3.        ]
[        nan         nan         nan         nan         nan -1.09861229
  0.          0.51082562  0.84729786  1.09861229]


/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in log
print(logndarray[0])
print('nan ==None? {}'.format(logndarray[0] is None))
nan
nan ==None? False
np.isnan(logndarray[0])
True

np.e

print(np.e)
print(np.log(np.e))
2.718281828459045
1.0

ndarrayのshape操作

ndarray = np.array([[1,2,3], [4,5,6], [7,8,9]])
print('array is :{}'.format(ndarray))
print("ndarray's shape is :{}".format(ndarray.shape)) #次元の数をrankという。
array is :[[1 2 3]
 [4 5 6]
 [7 8 9]]
ndarray's shape is :(3, 3)

np.expand_dims(nd.array, axis)

expanded_ndarray = np.expand_dims(ndarray, axis=0) #次元の追加
expanded_ndarray.shape
(1, 3, 3)

np.squeeze(ndarray)

squeezed_ndarray = np.squeeze(expanded_ndarray) #shapeの次元を1つなくす。
squeezed_ndarray.shape
(3, 3)

.flatten()

flatten_array = ndarray.flatten() #1列にする
print('flatten_array is :{}'.format(flatten_array))
print('ndarray is :{}'.format(ndarray))
flatten_array is :[1 2 3 4 5 6 7 8 9]
ndarray is :[[1 2 3]
 [4 5 6]
 [7 8 9]]

Numpy Arrayを保存、読み込む

np.save('ファイルパス', ndarray)

ndarray = np.array([
    [1,2,3,4],
    [10,20,30,40],
    [100,200,300,400]
])
np.save('saved_numpy', ndarray)

np.load('ファイルパス')

loaded_numpy = np.load('saved_numpy.npy')
loaded_numpy
array([[  1,   2,   3,   4],
       [ 10,  20,  30,  40],
       [100, 200, 300, 400]])
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0