チートシート (ラボクオリティなので、ご利用は自己責任でお願いします)
【 Numpy 】
属性  配列をつくる  各種操作など  欠損関連  数学・統計関連  ランダム・分布関連  表示  保存・読み込み 
属性
・属性

print('import numpy as np')
import numpy as np
a = np.arange(10).reshape(2,5)
print('a =', a)
print('形状')
print("a.shape")
print(a.shape)
print('================================')
print('総バイト数')
print("a.nbytes")
print(a.nbytes)
print('================================')
print('データ型')
print("a.dtype")
print(a.dtype)
print('================================')
print('型変換')
a = np.array([0,1,0,1,0])
print('a =', a)
print('int->bool型')
print("a.astype(bool)")
print(a.astype(bool))
print('================================')
print('float型')
print("a.astype(float)")
print(a.astype(float))
print('================================')
a = np.array([True, False, True])
print('a =', a)
print('bool->int型')
print("a.astype(int)")
print(a.astype(int))
属性に戻る

配列をつくる
基本的な配列をつくる  いろいろな配列をつくる
・基本的な配列をつくる

print('import numpy as np')
import numpy as np
print("np.arange(10)")
print(np.arange(10))
print('=================================')
print("np.array([1,2,3])")
print(np.array([1,2,3]))
print('=================================')
print("np.array(range(1,11))")
print(np.array(range(1,11)))
print('=================================')
print("np.array(range(10,0,-1))")
print(np.array(range(10,0,-1)))
配列をつくるに戻る

・いろいろな配列をつくる

値が0,1の配列

print('import numpy as np')
import numpy as np
print("np.zeros((3,3))")
print(np.zeros((3,3)))
print('===================')
print("np.ones((3,3))")
print(np.ones((3,3)))

単位行列

print('import numpy as np')
import numpy as np
print("np.eye(3)")
print(np.eye(3))

指定値で埋めた配列

print('import numpy as np')
import numpy as np
print("np.full((5,5), 3)")
print(np.full((5,5), 3))
配列をつくるに戻る

配列を繰り返す

print('import numpy as np')
import numpy as np
print("np.tile(np.arange(3), 3)")
print(np.tile(np.arange(5), 3))
print('==================================')
print('a = np.arange(9).reshape(3,3)')
a = np.arange(9).reshape(3,3)
print(a)
print("np.tile(a, (3,3))")
print(np.tile(a, (3,3)))

コピー(参照回避)

print('import numpy as np')
import numpy as np
a = np.arange(9).reshape(3,3)
print('print(a)')
print(a)
print('b = np.copy(a)')
b = np.copy(a)
print('b[1,1] = 100')
b[1,1] = 100
print('print(b)')
print(b)
print('print(a)')
print(a)

等間隔に区切る

print('import numpy as np')
import numpy as np
print('start, stop, num=50(default)')
print("np.linspace(0, 1).reshape(10,5)")
print(np.linspace(0, 1).reshape(10,5))
print('============================================================')
print("np.linspace(0, 10, 11)")
print(np.linspace(0, 10, 11))
print('============================================================')
print('stopの値を含まない')
print("np.linspace(0, 11, 11, endpoint=False)")
print(np.linspace(0, 11, 11, endpoint=False))
print('============================================================')
print("np.linspace(0, 1.0, 11)")
print(np.linspace(0, 1.0, 11))
配列をつくるに戻る

各種操作など

配列を変形する  配列を結合する  要素を追加する  要素の取得など  その他の操作など 


・配列を変形する

print('import numpy as np')
import numpy as np
print('形状を変える')
a = np.arange(10)
print('a =', a)
print("np.reshape(a, (2,5))")
print(np.reshape(a, (2,5)))
print('===================================')
print('-1は自動調整')
print("np.reshape(a, (2,-1))")
print(np.reshape(a, (2,-1)))
print('===================================')
print('メソッド')
print("a.reshape(2,5)")
print(a.reshape(2,5))
print('===================================')
print('フラット化、平坦化')
a = np.arange(10).reshape(2,5)
print('print(a)')
print(a)
print('参照')
print("a.reshape(-1)")
print(a.reshape(-1))
print("a.ravel()")
print(a.ravel())
print('===================================')
print('参照なし(order=C:C行, F:Fortran列)')
print("a.flatten()")
print(a.flatten())
print('===================================')
print('イテレータ')
print('for i in a.flat:')
print("    print(i, end=' ')")
for i in a.flat:
    print(i, end=' ')
各種操作などに戻る

・配列を結合する

print('import numpy as np')
import numpy as np
a = np.array([0,1,2,3,4])
b = np.array([5,6,7,8,9])
print('a =', a)
print('b =', b)
print('列で結合(column_stac)')
print("np.column_stack((a, b))")
print(np.column_stack((a, b)))
print('=========================')
print('行で結合(横)(hstack)')
print("np.hstack((a, b))")
print(np.hstack((a ,b)))
print('=========================')
print('行で結合(縦)(vstack)')
print("np.vstack((a, b))")
print(np.vstack((a, b)))
print('=========================')
print('concatnate')
c = np.vstack((a, b))
print('c =', c)
print('行で結合(横)')
print("np.concatenate((c, c), axis=1)")
print(np.concatenate((c, c), axis=1))
print('=========================')
print('行で結合(縦)')
print("np.concatenate((c, c), axis=0)")
print(np.concatenate((c, c), axis=0))
各種操作などに戻る

・要素を追加する

append(Pythonリストのほうが高速)

print('Pythonリストのほうが高速(jupyterlab)')
print('import numpy as np')
import numpy as np
print('numpy array')
a = np.arange(10)
print('a =', a)
print('a = np.append(a, 10)')
a = np.append(a, 10)
print(a)
print('======================================')
print('python list')
l = list(range(10))
print('l =', l)
print('l.append(10)')
l.append(10)
print(a)

insert

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('(array, index, value)')
print('a = np.insert(a, 10, 10)')
a = np.insert(a, 10, 10)
print(a)
各種操作などに戻る

・要素の取得など

インデックスで取得(スライス)

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
b = a[:5]
print('{:10}'.format('a[:5]'), b)
c = a[[0, 4, 8]]
print('{:10}'.format('a[0,4,8]'), c)
d = a[::2]
print('{:10}'.format('a[::2]'), d)
e = a[::-1]
print('{:10}'.format('a[::-1]'), e)

条件式・bool配列で取得(np.where)

print('import numpy as np')
import numpy as np
a = np.arange(5)
print('a =', a)
print('a[a > 2]\n->', a[a > 2])
print('======================================')
print('bool\n', 'a[[True, False, True, False, True]]\n->',
      a[[True, False, True, False, True]])
print('======================================')
print('np.where(条件式,代入)')
a = np.arange(10)
print('a =', a)
print('条件式のTrueインデックスを返す')
print('np.where(a>4)[0]\n->', np.where(a>4)[0])
print('======================================')
print('条件式で値を代入')
print('np.where(a>4, 1, 0)\n->', 
      np.where(a>4, 1, 0))

その他の要素取得(isin, unique)

print('import numpy as np')
import numpy as np
print('指定要素を取得、除外')
a = [0, 1, 2]
print('a =', a)
b = np.array([1, 2, 3, 4, 5])
print('b =', b)
print('bからaの値を取得\nb[np.isin(b, a)]->', b[np.isin(b, a)])
print('bからaの値を除外\nb[~np.isin(b, a)]->', b[~np.isin(b, a)])
print('=========================================================')
print('ユニーク要素取得(重複除外sort、index返す)')
print('np.unique([1,3,2,3,2,5], return_index=True)')
print('(unique, return_index)')
print(np.unique([1,3,2,3,2,5], return_index=True))
各種操作などに戻る

・その他の操作など

ソート  bool反転  ビニング  真偽判定  クリッピング  関数適用(vectorize)
その他 (カウント、index指定削除、検索、符号判定、3点リーダ)


ソート

print('import numpy as np')
import numpy as np
a = np.array([3, 1, 5, 2, 4])
print('a =', a)
print('{:17}'.format('a'), a)
print('{:17}'.format('np.sort(a)'), np.sort(a))
print('インデックス')
print('{:17}'.format('np.argsort(a)'), np.argsort(a))
print('{:17}'.format('a[np.argsort(a)]'), a[np.argsort(a)])

bool(符号)反転(チルダ)

print('import numpy as np')
import numpy as np
print('bool反転')
print('a = np.array([True, False, True])')
a = np.array([True, False, True])
print('print(~a)')
print(~a)
print('===================================')
print('符号反転')
print('a = np.array([100, 200, 300])')
a = np.array([100, 200, 300])
print('※-1する必要あり')
print('print(~(a-1))')
print(~(a-1))

ビニング(離散化)

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('bins: 区切りindex, right: <=どちらにするか')
print('0<=x<2, ...')
print('np.digitize(a, bins=[2,5,8], right=False)\n->',
      np.digitize(a, bins=[2,5,8], right=False))
print('===========================================')
print('0<x<=2, ...')
print('np.digitize(a, bins=[2,5,8], right=True)\n->',
      np.digitize(a, bins=[2,5,8], right=True))
各種操作などに戻る

真偽判定

print('import numpy as np')
import numpy as np
a = np.array([True, False, True])
print('a =', a)
print('Trueがあるか')
print("np.any(a)\n->", np.any(a))
print('========================')
print('すべてTrueか')
print("np.all(a)\n->", np.all(a))

クリッピング

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('(array, min, max)')
print("np.clip(a, 2, 7)\n->", np.clip(a, 2, 7))
print('==========================================')
a = np.array([-1, -0.5, 1.2, 0.2, -0.5, 0.8, 1.5])
print('a =', a)
print("np.clip(a, 0, 1)\n->", np.clip(a, 0, 1))

関数適用(vectorize, 高速)

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('f = lambda x: x**2')
f = lambda x: x**2
print('v_f = np.vectorize(f)')
v_f = np.vectorize(f)
print("v_f(a)\n->", v_f(a))
print('=========================================')
print('np.vectorizeとpandas.applyとの比較')
print('下記コードでは約4倍程度高速(jupyter lab)')
print('import pandas as pd')
import pandas as pd
print('df = pd.DataFrame(np.arange(10))')
df = pd.DataFrame(np.arange(10))
print('df[0].values =', df[0].values)
print('np.vectorize')
print('f = lambda x: x**2')
f = lambda x: x**2
print('v_f = np.vectorize(f)')
v_f = np.vectorize(f)
print('v_f(df[0])')
print(v_f(df[0]))
print('=========================================')
print('pandas.apply')
print("df[0].apply(lambda x: x**2)")
print(df[0].apply(lambda x: x**2).values)
各種操作などに戻る

その他

print('import numpy as np')
import numpy as np
# np.set_printoptions(precision=3, suppress=True)
print('ユニーク要素、カウント')
a = np.array([0,1,2,2,1,0,0,1,1,2])
print('a =', a)
print("np.unique(a, return_counts=True)")
print(np.unique(a, return_counts=True))
print('==================================================')
print('インデックス指定で削除')
a = np.arange(10)
print('a =', a)
print("a = np.delete(a, range(5))")
a = np.delete(a, range(5))
print('a =', a)
print('==================================================')
print('検索(bool配列)')
a = np.arange(5)
print('a =', a)
print("np.isin(a, [1,2,3])")
print(np.isin(a, [1,2,3]))
print('==================================================')
print('符号判定')
a = np.array([-10, 0, 10, -0.1, 0.1])
print('a =', a)
print("np.sign(a)")
print(np.sign(a))
print('==================================================')
print('3点リーダ(Ellipsis)')
a = np.arange(27).reshape(3,3,3)
print('a =\n', a)
print('==================================================')
print("a[:, :, 0]")
print(a[:, :, 0])
print('==================================================')
print("a[..., 0]")
print(a[..., 0])
print('==================================================')
print("a[Ellipsis, 0]")
print(a[Ellipsis, 0])
print('==================================================')
print("a[0, ..., 0]")
print(a[0, ..., 0])
print('==================================================')
print("a[0, Ellipsis, 0]")
print(a[0, Ellipsis, 0])
各種操作などに戻る

欠損関連

np.nan  欠損値を確認  欠損値を埋める  欠損値を取り除く 


・np.nan

print('import numpy as np')
import numpy as np
print("print(np.nan)")
print(np.nan)
print('==================================')
print("type(np.nan)")
print(type(np.nan))
print('==================================')
print("if np.nan: print('bool:', True)")
if np.nan: print('bool:', True)
print('==================================')
print('np.nan == np.nan ->', np.nan==np.nan)
print('==================================')
print('np.nan in [np.nan] ->', np.nan in [np.nan])
print('==================================')
print('np.nan is np.nan ->', np.nan is np.nan)
欠損関連に戻る

・欠損値を確認

print('import numpy as np')
import numpy as np
print("a = np.array([1, 2, 3, float('NaN'), float('nan')])")
a = np.array([1, 2, 3, float('NaN'), float('nan')])
print(a)
print('bool配列を返す')
print("np.isnan(a)")
print(np.isnan(a))
欠損関連に戻る

・欠損値を埋める

print('import numpy as np')
import numpy as np
print("a = np.array([1,2,3,4,float('nan')])")
a = np.array([1,2,3,4,float('nan')])
print(a)
print("np.nan_to_num(a, nan=100)")
print(np.nan_to_num(a, nan=100))
print('=====================================')
print("np.nan_to_num(a, nan=np.nanmean(a))")
print(np.nan_to_num(a, nan=np.nanmean(a)))
print('=====================================')
print("np.where(np.isnan(a), 100, a)")
print(np.where(np.isnan(a), 100, a))
欠損関連に戻る

・欠損値を取り除く

print('import numpy as np')
import numpy as np
print("a = np.array([1,2,3,4,float('nan')])")
a = np.array([1,2,3,4,float('nan')])
print(a)
print("a[~np.isnan(a)]")
print(a[~np.isnan(a)])
print('======================================')
a = np.array([[1,2,float('nan')],[4,float('nan'),6],[7,8,9]])
print('a =\n', a)
print('行の場合')
print("a[~np.isnan(a).any(axis=1)]")
print(a[~np.isnan(a).any(axis=1)])
print('======================================')
print('列の場合')
print("a[:, ~np.isnan(a).any(axis=0)]")
print(a[:, ~np.isnan(a).any(axis=0)])
欠損関連に戻る

数学・統計関連

配列演算など(ブロードキャスト)  数学関連  三角関数  対数関連  数値丸め  統計関連 


・配列演算など(ブロードキャスト)

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print("a + 1")
print(a + 1)
print('=============================================')
print("a - 1")
print(a - 1)
print('============================================')
print("a * 10")
print(a * 10)
print('============================================')
print("a / 10")
print(a / 10)
print('============================================')
print("a * a")
print(a * a)
print('============================================')
print("a[1:] / a[1:]")
print(a[1:] / a[1:])
print('============================================')
a = np.arange(9).reshape(3,3)
print('a =\n', a)
print('*[1,2,3]\n', a * np.array([1,2,3]))
print('============================================')
print('*[[1],[2],[3]]\n', a * np.array([1,2,3]).reshape(3,1))
print('============================================')
print('インデックス指定で加算')
a = np.arange(10)
print('a =', a)
print("np.add.at(a, [0,5], 100)")
np.add.at(a, [0,5], 100)
print(a)
数学・統計関連に戻る

・数学関連

print('import numpy as np')
import numpy as np
a = np.arange(9).reshape(3,3)
print('a =\n', a)
print('和')
print("np.sum(a)")
print(np.sum(a))
print('===============================')
print('和(行方向、縦)')
print("np.sum(a, axis=0)")
print(np.sum(a, axis=0))
print('===============================')
print('和(列方向、横)')
print("np.sum(a, axis=1)")
print(np.sum(a, axis=1))
print('===============================')
print('累積和')
print("np.cumsum(a)")
print(np.cumsum(a))
print('===============================')
print('差分')
print("np.diff(a)")
print(np.diff(a))
print('===============================')
print('積(行方向、縦)')
print("np.prod(a, axis=0)")
print(np.prod(a, axis=0))
print('===============================')
print('積(列方向、横)')
print("np.prod(a, axis=1)")
print(np.prod(a, axis=1))
print('===============================')
print('累積積(列方向、横)')
print("np.cumprod(a, axis=1)")
print(np.cumprod(a, axis=1))
print('===============================')
print('累乗')
print("np.power(a, 2)")
print(np.power(a, 2))
print('===============================')
print('平方根')
print("np.sqrt(a).round(2)")
print(np.sqrt(a).round(2))
print('===============================')
print('絶対値')
print("np.abs([-1, 1, -2, 2])")
print(np.abs([-1, 1, -2, 2]))
数学・統計関連に戻る

・三角関数

print('import numpy as np')
import numpy as np
print('np.pi(radian:ラジアン)=180°(theta:角度)')
print('角度をラジアンに変換')
print('theta = 45')
theta = 45
print('radian = np.radians(theta)')
radian = np.radians(theta)
print("radian.round(5)")
print(radian.round(5))
print('sin45°')
print("np.sin(radian).round(5)")
print(np.sin(radian).round(5))
print('==============================================')
print('cos45°')
print("np.cos(radian).round(5)")
print(np.cos(radian).round(5))
print('==============================================')
print('tan45°')
print("np.tan(radian).round(5)")
print(np.tan(radian).round(5))
print('==============================================')

import matplotlib.pyplot as plt
import japanize_matplotlib
a = np.arange(0, 10, 0.01)
plt.style.use('dark_background')
plt.figure(figsize=(5,3))
plt.plot(a, np.sin(a), label='sin')
plt.plot(a, np.cos(a), label='cos')
plt.xlabel('a')
plt.title('sin-cos曲線')
plt.legend()
plt.show()
数学・統計関連に戻る

・対数関連

print('import numpy as np')
import numpy as np
print("a = np.array([np.e**0, np.e**1, np.e**2])")
a = np.array([np.e**0, np.e**1, np.e**2])
print('a =', a)
print('対数(eの乗数)')
print("np.log(a)")
print(np.log(a))
print('===============================================')
print('import math')
import math
print('math.log')
print("[math.log(i) for i in a]")
print([math.log(i) for i in a])
print('===============================================')
print('0がある場合')
print('np.log1p')
print("a = np.array([0, np.e**0, np.e**1, np.e**2])")
a = np.array([0, np.e**0, np.e**1, np.e**2])
print('a =', a.round(3))
print("np.log1p(a).round(3)")
print(np.log1p(a).round(3))
print('===============================================')
print('対数を戻す')
print('log')
print("a = np.array([0, np.e**0, np.e**1, np.e**2])")
a = np.array([0, np.e**0, np.e**1, np.e**2])
print("a.round(3)")
print(a.round(3))
print("np.exp(np.log(a[1:])).round(3)")
print(np.exp(np.log(a[1:])).round(3))
print('===============================================')
print('log1p')
print("np.expm1(np.log1p(a)).round(3)")
print(np.expm1(np.log1p(a)).round(3))
数学・統計関連に戻る

・数値丸め

print('import numpy as np')
import numpy as np
a = [0.995, 0.994]
print(a)
print('round', np.round(a, 2))
print('===============================')
print('偶数丸め注意')
a = [0.5, 1.5, 2.5, 3.5, 4.5]
print('a =', a)
print("np.round(a)")
print(np.round(a))
print('===============================')
a = [-1.8, 0.8, 1.5]
print(a)
print('0方向に近い整数にまとめる')
print("np.fix(a)")
print(np.fix(a))
print('===============================')
print('小さい方にまとめる')
print("np.floor(a)")
print(np.floor(a))
print('===============================')
print('大きい方にまとめる')
print("p.ceil(a)")
print(np.ceil(a))
print('===============================')
print('小数点切り捨て')
print("np.trunc(a)")
print(np.trunc(a))
数学・統計関連に戻る

・統計関連

print('import numpy as np')
import numpy as np
print("np.set_printoptions(precision=3)")
np.set_printoptions(precision=3)
a = np.arange(10)
print('a =', a)
print('平均')
print("np.mean(a)")
print(np.mean(a))
print('=======================================')
print('最大小値')
print("np.max(a), np.min(a)")
print(np.max(a), np.min(a))
print('=======================================')
print('最大最小インデックス')
print("np.argmax(a), np.argmin(a)")
print(np.argmax(a), np.argmin(a))
print('=======================================')
print('中央値')
print("np.median(a)")
print(np.median(a))
print('=======================================')
print('パーセンタイル(分位点)')
print("np.percentile(a, [25,50,75])")
print(np.percentile(a, [25,50,75]))
print('=======================================')
print('分散、不偏分散')
print("np.var(a, ddof=0), np.var(a, ddof=1)")
print(np.var(a, ddof=0).round(3), 
      np.var(a, ddof=1).round(3))
print('=======================================')
print('標準偏差、不偏標準偏差')
print("np.std(a, ddof=0), np.std(a, ddof=1)")
print(np.std(a, ddof=0).round(3), 
      np.std(a, ddof=1).round(3))
print('=======================================')
print('共分散')
b = np.arange(9,-1,-1)
print('b =', b)
print("np.cov(a, b)")
print(np.cov(a, b))
print('=======================================')
print('相関係数')
print("np.corrcoef(a, b)")
print(np.corrcoef(a, b))
print('=======================================')
print('nanある場合')
a = np.array([0, 1, 2, 3, np.nan, 5])
print('a =', a)
print("np.nanmean(a)")
print(np.nanmean(a))
数学・統計関連に戻る

ランダム・分布関連

各種ランダム分布  形状指定  ランダム取得  データシャッフル  その他 


・各種ランダム分布

# 表示するもの以外コメントアウト
import numpy as np
import matplotlib.pyplot as plt

# 乱数指定(再現性)
np.random.seed(0)

# ランダム値を指定のサイズで生成
# 範囲:[0.0, 1.0) 0以上1未満、一様分布
a = np.random.rand(10000)
# a = np.random.random(10000)
# a = np.random.random_sample(10000)
# 範囲:[low, high)、一様分布
# a = np.random.uniform(1, 2, 10000)
# 範囲:[low, high]、一様分布、整数
# a = np.random.randint(1, 101, 10000)
# 平均・標準偏差指定、正規分布
# a = np.random.normal(0, 1, 10000)
# 平均0・標準偏差1、正規分布
# a = np.random.randn(10000)
# 平均・スケール(>0)指定、ロジスティック分布
# a = np.random.logistic(0, 1, 10000)
# 二項分布(試行回数, 確率, サンプル数)
# a = np.random.binomial(1, 0.5, 10000)
# ポアソン分布(期待値, サンプル数)
# a = np.random.poisson(1.0, 10000)
# カイ二乗分布(自由度, サンプル数)
# a = np.random.chisquare(1, 10000)
# スチュ―デントt分布(自由度, サンプル数)
# a = np.random.standard_t(10, 10000)
# F分布(分子自由度, 分母自由度, サンプル数)
# a = np.random.f(5, 10, 10000)

plt.style.use('dark_background')
plt.hist(a, bins=50, ec='b')
plt.show()
ランダムに戻る

・形状指定

# 表示するもの以外コメントアウト
import numpy as np
a = np.random.rand(3,3)
# a = np.random.random((3,3))
# a = np.random.random_sample((3,3))
# a = np.random.uniform(1, 2, (3,3))
# a = np.random.randint(1, 101, (3,3))
# a = np.random.normal(0, 1, (3,3))
# a = np.random.randn(3,3)
# a = np.random.logistic(0, 1, (3,3))
# a = np.random.binomial(1, 0.5, (3,3))
# a = np.random.poisson(1.0, (3,3))
# a = np.random.chisquare(1, (3,3))
# a = np.random.standard_t(10, (3,3))
# a = np.random.f(5, 10, (3,3))
print(a)
ランダムに戻る

・ランダム取得

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('(配列, 取得数)')
print("np.random.choice(a, 10)")
print(np.random.choice(a, 10))
print('=========================================================')
print('replace=False:重複なし、p=確率リスト(sum=1)')
rate = [0.2, 0.2, 0.2, 0.1, 0.1, 0.05, 0.05, 0.05, 0.03, 0.02]
print("rate")
print(rate)
print("np.random.choice(a, 10, replace=True, p=rate)")
print(np.random.choice(a, 10, replace=True, p=rate))
ランダムに戻る

・データシャッフル

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print("np.random.permutation(a)")
print(np.random.permutation(a))
print('==========================')
print("np.random.shuffle(a)")
np.random.shuffle(a)
print("print(a)")
print(a)
ランダムに戻る

・その他

print('import numpy as np')
import numpy as np
print('ランダムなワンホット(one-hot)配列をつくる')
print('1の数、確率リスト(sum=1)、つくる数')
print("np.random.multinomial(1, [0.1, 0.1, 0.5, 0.2, 0.1], 2)")
print(np.random.multinomial(1, [0.1, 0.1, 0.5, 0.2, 0.1], 2))
ランダムに戻る

表示
・表示設定変更

print('import numpy as np')
import numpy as np
print('import pprint')
import pprint
print('オプション表示')
print("np.get_printoptions()")
pprint.pprint(np.get_printoptions())
print('=======================================')
print('threshold: 表示する要素数')
print("np.set_printoptions(threshold=6)")
np.set_printoptions(threshold=6)
print("np.arange(10)")
print(np.arange(10))
print('すべて表示')
print("np.set_printoptions(threshold=np.inf)")
np.set_printoptions(threshold=np.inf)
print("np.arange(10)")
print(np.arange(10))
print('=======================================')
print('precision: 小数点以下表示桁数')
print("np.set_printoptions(precision=3)")
np.set_printoptions(precision=3)
print("np.array([1,1,1]) / 3")
print(np.array([1,1,1]) / 3)
print('=======================================')
print('suppress: 指数表示(Trueでなし)')
print('np.set_printoptions(suppress=False)')
np.set_printoptions(suppress=False)
print("np.set_printoptions(precision=6)")
np.set_printoptions(precision=6)
print("np.array([1,1,1]) / 1000000")
print(np.array([1,1,1]) / 1000000)
print('=======================================')
print("np.set_printoptions(suppress=True)")
np.set_printoptions(suppress=True)
print("np.array([1,1,1]) / 1000000")
print(np.array([1,1,1]) / 1000000)
表示に戻る

保存・読み込み

npy 


・npyファイルの保存・読み込み

print('import numpy as np')
import numpy as np
a = np.arange(10)
print('a =', a)
print('保存')
print("np.save('data', a)")
np.save('data', a)
print('読み込み')
print("a = np.load('data.npy')")
a = np.load('data.npy')
print("print(a)")
print(a)
保存・読み込みに戻る