LoginSignup
1
1

More than 3 years have passed since last update.

numpyを使ってみる

Posted at

numpyを使ってみます。

import numpy as np

np.array

配列を作ります。

sample_array = np.array([1,2,3,4,5])
sample_array

shapeに関して

sample_array.shape # (5,)

sample_array.reshape(-1,1).shape # (5, 1)

reshapeのエラーメッセージにはだいたいこれで対応。

文字列と数字の格納

np.array([1,2,"A"])
# array(['1', '2', 'A'], dtype='<U21')

数値型と文字列型を同時に入れると、全て文字列として扱われる。

np.zeros()

0の連続する配列を作ります。初期化配列に使ったりする。

np.zeros(10)
# array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

# 2行3列を0で埋めておく
np.zeros([2,3])

# 1もできる
np.ones(5)
# array([1., 1., 1., 1., 1.])

演算

リストで計算するのと比べると、便利な演算機能です。

sample_array + 2
# array([3, 4, 5, 6, 7])

リストと比較

sample_list = [1,2,3,4,5]
sample_list + 2 # エラー
sample_list = [1,2,3,4,5]
sample_list + [2,2,2,2,2] 
# [3, 4, 5, 6, 7, 2, 2, 2, 2, 2]
sample_list = [1,2,3,4,5]
for i in range(len(sample_list)):
    sample_list[i] = sample_list[i] + 2
print(sample_list)

統計量

# sum
sample_array.sum()
np.sum(sample_array)

# mean
sample_array.mean()
np.mean(sample_array)

# var
sample_array.var()
np.var(sample_array)

# std
sample_array.std()
np.std(sample_array)

二次元配列

sample_array_2 = np.array(
        [[1,2,3,4,5],
        [6,7,8,9,10]])

sample_array_2
# array([[ 1,  2,  3,  4,  5],
#      [ 6,  7,  8,  9, 10]])

sample_array_2.shape # (2, 5)

np.arange

数列の作成

# 初項1、公差1の等差数列を6にあたるまで作る(6は含まず)
np.arange(start = 1, stop = 6, step = 1)
# array([1, 2, 3, 4, 5])

np.arange(start=0.1, stop=0.8, step=0.2)
# array([0.1, 0.3, 0.5, 0.7])

np.linspace

数列の作成

# -2から2までの等差数列を連続的に作る
np.linspace(-2,2)

# plotで直線・曲線を描く際にx軸でたどる範囲に指定するような使い方もされる
# 0から10の区間に数値を等間隔で11個配置した数列
np.linspace(0, 10, 11)
# array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

np.tile

同じ値を複数格納

np.tile("A",5) # array(['A', 'A', 'A', 'A', 'A'], dtype='<U1')
np.tile(0,4) # array([0, 0, 0, 0])
np.zeros(4) # 同じ

np.random.choice

sample_array = np.array([1,2,3,4,5])


# 3つの非復元抽出
np.random.choice(sample_array, size=3, replace = False)

# 3つの復元抽出
np.random.choice(sample_array, size=3, replace = True)

np.random.seed()

# randomの出力を固定する
np.random.seed(1)
np.random.choice(sample_array, size=3, replace = False)

行列の計算もとても便利なので、そのうち追記します。

1
1
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
1