これは難しい
グラフ
[基本]
●プロットする(簡易)
from matplotlib import pylab as plt
plt.plot(X,Y)
plt.xlim([x0,x1])#範囲を指定
plt.ylim([y0,y1])
plt.xscale('log')#log scaleにする(こいつらいっぺんに指定できんのか?)
plt.yscale('log')

●基本フォーマット(論文用:Fig>Axes>Axisらしい)
from matplotlib import pylab as plt
fig, ax = plt.subplots(figsize=(4,3))#fig, axを同時に作っているらしい
plt.rcParams['font.family'] = 'Times New Roman' #フォントを変える
plt.rcParams['mathtext.fontset'] = 'stix' #フォントを変える2
ax.tick_params(axis="both",which="both",direction="in", top = True, right=True) #ticsを上下両サイド内側にする
ax.set_title("TITLE") #タイトル
ax.set_xlim(x0,x1) #x軸の範囲設定
ax.set_xscale("log") #x軸をlog scaleに
ax.set_xlabel("XXX",fontsize=14)#ラベルをつける
ax.plot(X,Y)
ax.legend(loc=2,labelspacing=0.1)#loc=(1,2,3,4)=(右上,左上,左下,右下)
fig.savefig("fig_FIGURE.pdf", bbox_inches='tight') #pdfに保存する

●Titleの高さを変える
ax.set_title("TITLE",pad=20)
●字を書く
ax.text(x0,y0,"XXX",color="black",fontsize=14,rotation=0)
●字を囲いの中に書く
boxdic = {"facecolor":"w","edgecolor":"k","boxstyle":"Round","linewidth":1}
ax.text(x0,y0,"XXX",bbox=boxdic)
●数式を打ちたい(Texみたいな)
ax.text(x0,y0,"\\alpha")#\\と重ねるのがポイント
◎点を打つ
 ax.plot([x0,x1,...],[y0,y1,...],ls="",marker="o",ms=1,mew=0.5,mec="black")#ms=markersize,mew=markeredgewidth,etc...,scatterとの違いもよくわからん
◎矢印を引く
 ax.annotate("XXX",[x0,y0],[x1,y1],arrowprops=dict(width=5,headwidth=15,headlength=10,facecolor="red",edgecolor="black"))
 ax.annotate("XXX",[x0,y0],[x1,y1],arrowprops=dict(arrostyle="<|-|>",color="black"))#両矢印(あまりフレキシブルでない)
●塗りつぶし
ax.fill_between(X,Y1,Y2,color="red",alpha=0.5)#2つのグラフの間を塗る
ax.fill_betweenx(Y,X1,X2,color="red",alpha=0.5)#2つのグラフの間を塗る
ax.fill([x0,x1,x2],[y0,y1,y2],color="red",alpha=0.5)#よりフレキシブル
●エラーバー付きのプロット
ax.errorbar(X,Y,xerr=[Xlow,Xhigh],yerr=[Ylow,Yhigh],fmt="o",ms=1,capsize=1,ecolor="red",markeredgecolor="red")#Xlowとかはエラー幅
●エラーバー付きのプロット(logplotの場合の注意点)
1.qに対してQ=log_10(q)をプロットしてエラーバーをつけたいとする
2.qのエラーをdqとするとdQ=dq/q/log_e(10)となる
3.エラーバーの上端と下端の中心値からの差はdQ_high=q(10**dQ-1),dQ_low=q(1-10**-dQ)で与えられる(もっと簡単な方法ないんかいな?)
●x=Xの線を引く
ax.vlines(X,ymin,ymax)
●y=Yの線を引く
ax.hlines(Y,xmin,xmax)

●gridを引く
ax.grid(which = "major", axis = "both", color = "black", alpha = 0.25, linestyle = "-", linewidth = 0.5)
●軸を2つ設定する
secax = ax.secondary_yaxis('right', functions=(lambda x: x**2, lambda x: np.sqrt(x)))#右側の軸をy**2で設定する(functionsは函数と逆関数)
secax.tick_params(axis="both",which="both",direction="in", top = True, right=True)#目盛を内部にする
secax.set_ylabel("",fontsize=12)
●軸を2つ設定する (等級と光度の場合に上がうまく対応しない)
ax2 = ax.twinx()
ax2.tick_params(axis="both",which="both",direction="in", right=True)
ax2.set_ylabel("",fontsize=12)
●Legendの位置を任意に設定
ax.legend(bbox_to_anchor=(x0,y0))#(0,0)を左下、(1,1)を右上としてボックスの位置を指定。この場合locを追加するとボックスのどこを合わせるかという意味になるので注意
●Legendの順序を自由に設定する(errorbarとplotだとplotが優先されるので)
handles,labels = ax.get_legend_handles_labels()#使い方はよくわからんがlist番号とplotなどの対応を意識する
handles = [handles[2], handles[3], handles[0], handles[1]]
labels = [labels[2], labels[3], labels[0], labels[1]]
ax.legend(handles,labels,loc=1,labelspacing=0.1)
●Legendの凡例を複数列で設置
ax.legend(ncol=2)
●Legendの凡例どうしの間隔を調整する(複数列のとき)
ax.legend(columnspacing=1)
●Legendの線と名前の間隔を調整する
ax.legend(handletextpad=0.2)
●Legendの線の長さを変える
ax.legend(handlelength=2)
●Ledendの透明度を変更する
ax.legend(XXX).get_frame().set_alpha(0.9)
●Ledendの枠を無くす
ax.legend(frameon=False)
●Ledendで複数のデータでラベルを共有させる(○ xlabel, みたいな)
from matplotlib.legend_handler import HandlerLine2D, HandlerTuple
p0, = ax.plot(x0,y0,marker="o")
p1, = ax.plot(x1,y1,marker="x")
ax.legend([(p0,p1),(p2,p3),...], ["Label0","Label2"], numpoints=1,handler_map={tuple: HandlerTuple(ndivide=None)})
●Legendを複数にわける
hans, labs = ax.get_legend_handles_labels()#各々の情報が格納される
legend1 = ax.legend(handles=hans[:i],labels=labs[:i])#i番目のplot前後で分けるとき
legend2 = ax.legend(handles=hans[i:],labels=labs[i:])
ax.add_artist(legend1)

目盛あれこれ
●目盛の文字の高さを変更する
ax.tick_params(axis="both",which="both",direction="in", top = True, right=True, pad=20)
●目盛の文字の大きさを変更する
ax.tick_params(axis="both",which="both",direction="in", top = True, right=True, labelsize=20)
●目盛(major ticks)を任意に設定する
ax.set_xticks(ticks=[X0,X1,X2,...])
ax.set_xticklabels(labels=["X0","X1","X2",...])
●目盛(minor ticks)を任意に設定する
ax.set_xticks(ticks=[X0,X1,X2,...],minor=True)
ax.set_xticklabels(labels=["X0","X1","X2",...],minor=True)
●目盛数値を消す
ax.set_xticklabels(labels=[])
●目盛の間隔を任意で設定する
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
ax.xaxis.set_major_locator(MultipleLocator(5))#大目盛:dx=5
ax.xaxis.set_minor_locator(MultipleLocator(1))#小目盛:dx=1
●対数目盛(major and minor tick)を任意に設定する
import matplotlib.ticker
ax.xaxis.set_major_locator(matplotlib.ticker.LogLocator(numticks=20))#numticksが表示したい目盛数よりも大きいこと
ax.xaxis.set_minor_locator(matplotlib.ticker.LogLocator(numticks=20, subs=(.1,.2,.3,.4,.5,.6,.7,.8,.9)))
●対数目盛(数値)を"2x10^1"とかから"20"と表示する
from matplotlib.ticker import ScalarFormatter
ax.xaxis.set_major_formatter(ScalarFormatter())#major=>minorでminor ticks
●対数目盛(数値)を消す
from matplotlib.ticker import NullFormatter
ax.xaxis.set_major_formatter(NullFormatter())#major=>minorでminor ticks

◎対数目盛(major and minor tick)を任意に設定する(to be erased)
 import matplotlib.ticker
 ax.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10,numticks=10))#major tickを設置する(mojorの場合は上でもOK)
 ax.xaxis.set_minor_locator(matplotlib.ticker.LogLocator(base=10,subs=(2,3,4,5,6,7,8,9),numticks=10))#minor tickを2,...,9まで設置する
 ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())#minor tickにはなぜか必要
◎目盛の書式を(1x10から10とかにする:対数)
 import matplotlib
 ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
◎さらに小数点などを変更したい(0.1,1.0,10.0から0.1,1,10とかにする)
 import matplotlib.ticker as ticker
 def major_formatter(x, pos):
 if y<1:
  return x
 else:
  return "%.0f" % x
 ax.yaxis.set_major_formatter(ticker.FuncFormatter(major_formatter))
 ax.set_yticks([0.1,1,10])

カラーバー
cmap = mpl.pyplot.get_cmap("rainbow",N)#Nは分割数
fig.subplots_adjust(right=0.9)#分布図と同じ
cbar_ax = fig.add_axes([0.915, 0.125, 0.02, 0.755])#分布図と同じ
norm = mpl.colors.SymLogNorm(2,vmin=1,vmax=1000)#色の規格化をlogscaleで行う
cb = mpl.colorbar.ColorbarBase(cbar_ax,cmap=cmap,norm=norm,orientation='vertical',ticks = [1,10,100,1000])
cb.ax.set_ylabel("XXX")
cb.ax.minorticks_off()###これもっと工夫できるかも

[色]
●グラデーション(数値に対応して配色する)
import matplotlib.cm as cm
Color = cm.XXX(value) #XXX:hsv,jetなど、value:数値
●定番カラー(colorblindness対応)
Color = ["#648FFF","#785EF0","#DC267F","#FE6100","#FFB000"]
●12色(冠位十二階:あまり見栄えはよくない)
Color = ["purple","royalblue","blue","dodgerblue","red","pink","yellow","khaki","white","gainsboro","black","gray"]

ヒストグラム
◎ヒストグラムを描く(logの場合、予めx-axisをlogscaleにしておく)
 ax.hist(X,bins=np.logspace(-1,1,21),histtype="bar")
◎ヒストグラム付き散布図を描く
 from mpl_toolkits.axes_grid1 import make_axes_locatable
 fig, ax = plt.subplots(figsize=(4,4))#以降で普通に散布図を描く
 divider = make_axes_locatable(ax)#これでaxに追加で図を書くようにしているらしい
 axHistx = divider.append_axes("top", 0.5, pad=0.)
 axHisty = divider.append_axes("right", 0.5, pad=0.)#以降でヒストグラムをaxのように書いていけばいい
 axHistx.hist(X,bins=(X0,X1,10),color="red")
 axHisty.hist(Y,bins=(Y0,Y1,10),color="red",orientation='horizontal')

[分布図(density plot)]
●データの作成(順番注意)
for y in Y:
 for x in X:
●density plotの基本((x,y,z)でz場をプロットする,colorは離散的)
X,Y = np.meshgrid(x,y)#これちゃんとやる
cs = ax.contourf(X,Y,z,levels=[z0,z1,z2,...],cmap=cm.viridis)
cbar = fig.colorbar(cs,ticks=[z0,z1,z2,...],aspect=30,pad=0.03)#color barをつける
cbar.ax.set_ylabel(Z)#color barのラベルをつける
●countourを描く
X,Y = np.meshgrid(x,y)
ax.contour(X,Y,z,levels=[z0,...],colors="k",linestyles=["solid"])
●カラーバーを独立に設置(複数の図で共通のカラーバーを使う場合)
cs = ax[i].contourf(X,Y,z)#これでカラーバーのスケールを取得
fig.subplots_adjust(right=0.9)#図の右端を左へ寄せる
cbar_ax = fig.add_axes([0.9, 0.1, 0.01, 0.7])#カラーバーの位置とサイズを直接与える([x,y,width,height])
cbar = fig.colorbar(cs, cax=cbar_ax)
cbar.ax.set_ylabel("XXX")
●カラーバーを各図に設置(複数の図でカラーバーを使う場合)
cs = axes[i].contourf(X,Y,z[i],levels=[z0,z1,z2,...],cmap=cm.viridis)
cbar = fig.colorbar(cs,ax=axes[i],ticks=[z0,z1,z2,...],aspect=30,pad=0.03)#color barをつける
●カラーバーの目盛数字(ticks)のサイズ、位置を変更
cbar.ax.tick_param(labelsize=10,pad=10)
●カラーバーを横向けにして図の中に設置(Matsumoto&Piran2023:Fig.9)
cs = axes[i].contourf(X,Y,z)
cbar_ax = fig.add_axes([x,y,width,height])#カラーバーの位置を調整
cbar = fig.colorbar(cs,cax=cbar_ax,orientation='horizontal',ticks=[z0,...])#カラーバーを横向けにする
cbar_ax.xaxis.set_ticks_position("top")#カラーバーの目盛を上に設置
cbar_ax.set_xlabel("XXX",labelpad=-33,fontsize=12)#ラベルも上に設置

[複数の図をつくる]
●上下2段のみ
fig, axes = plt.subplots(2,1,figsize=(4,3))
●サイズ(比)を変更したいとき
fig, axes = plt.subplots(2,1,gridspec_kw={"height_ratios":[1,3]},figsize=(4,3))#縦(横の場合は"width_ratios"))
●x軸を共通にする
fig, axes = plt.subplots(2,1,figsize=(4,3),sharex=True)
●上下の図の間隔(spacing)を変更
plt.subplots_adjust(hspace=0)#完全にくっつける場合
●各図のylabelの位置をそろえる
fig.align_labels([axes[0],axes[1],...])

複数の図をつくる2(ほんまにいっぱい)
●大量の図をつくる(MxN個並べてまとめて処理する場合)
fig, axes = plt.subplots(M,N,figsize=(1,1))
for i in range (M):
 for j in range (N):
  axes[i][j].plot(X,Y)
●図の数がちょうどいいときじゃないとき
axes[i][j].axis("off")
◎Loopとtex式の両立(今までlabel=f"X={XXX[i]}"とかでやってたから添字とかつけられんかった)
 axes[i].set_title("$X_{i}=$%f" %(XXX[i]))#とすりゃいい
◎共通のタイトルをつける
 fig.suptitle

媒介変数によって色が変化する曲線を描く((x(t),y(t))をtによって色を変える=>x,yを区切って大量の短いグラフとする)
 #ax=plt.XXXとかやっておく
 import matplotlib.cm as cm
 from matplotlib.collections import LineCollection
 from matplotlib.colors import ListedColormap, BoundaryNorm
 points = np.array([x, y]).T.reshape(-1, 1, 2)
 segments = np.concatenate([points[:-1], points[1:]], axis=1)
 norm = plt.Normalize(t.min(), t.max())#色付するために媒介変数tで規格化する
 lc = LineCollection(segments, cmap='jet', norm=norm)
 lc.set_array(dydx)
 lc.set_linewidth(5)
 line = ax.add_collection(lc)
 fig.colorbar(line, ax=ax)

出力
◎変数を文字列に埋め込む方法
 n=1
 print("{}".format(n))
◎数値の書式を指定する方法(.1f=小数第一位,.1e=同じく(1.1e+10),.1g=1桁まで)
 m=1.1
 n=1.1
 print("m={0:.1f},n={1:.1e}".format(m,n)
◎数値Xを有効数字N桁で四捨五入して整数値で出力する(もっといい方法ありそう)
 Str = str(int(X))#文字列に変換
 Len = int(len(Str)-1)#桁数を得る
 X = int(round(X/10**Len,N-1)*10**Len)

計算
●求根(函数f(x)=0の解を[x1,x2]の範囲で探す,defaultの精度は1.e-12くらい)
from scipy import optimize
para = (X,Y,...) #f(x)の他の引数があるとき
optimize.brentq(f, x1, x2, args=para)

●内挿(1次元:x_data,y_dataを内挿する,内挿函数y_intはnp.arrayを引数に取れる)
from scipy import interpolate
y_int = interpolate.interp1d(x_data, y_data)#線形内挿
y_int = interpolate.interp1d(x_data, y_data,kind="cubic")#三次関数

●内挿(2次元:x_data,y_data,z_dataを内挿する,内挿函数y_intはnp.arrayを引数に取れる)
from scipy import interpolate
X_data,Y_data = np.meshgrid(x_data,y_data)
y_int = interpolate.interp2d(X_data, Y_data, z_data, kind="linear")#線形内挿
y_int = interpolate.interp2d(X_data, Y_data, z_data, kind="cubic")#三次関数

●ODEを解く(dY/dt=F(Y,t))
from scipy.integrate import solve_ivp
def ODE(t,Y,a)#a:パラメータ
 Y0,Y1 = Y
 dY0dt = F0(Y0,Y1,t)
 dY1dt = F1(Y0,Y1,t)
 return [dY0dt,dY1dt]
IC = [Y0_ini,Y1_ini] #初期値
time = np.linspace(t0,t1,N)
SOL = solve_ivp(lambda t,y:ODE(t,y,a),[time[0],time[-1]],IC,t_eval=list(time))
t = SOL.t
Y0,Y1 = SOL.y

●ODEを解く2(上のセットアップで条件:Event(t,Y)が0以下,を満たせば積分を終了する)
def Event(t,Y,a):
 return Y0
event = lambda t,Y:Event(t,Y,a)#parameter aがある場合
event.terminal=True
SOL = solve_ivp(lambda t,y:ODE(t,y,a),[time[0],time[-1]],IC,t_eval=list(time),events=event)

●最小化(函数fをparameter(a,b)のもとで最小化する)
import scipy
from scipy import optimize
bounds = ((a0,a1),(b0,b1))#範囲が大きいときは対数とれ
param = scipy.optimize.brute(f,ranges=bounds,Ns=20)
a,b = para

●微分(函数F(x)の導関数のx=x0での値)
from scipy.misc import derivative
dfdx = derivative(F,x0,dx=1.e-10)

●積分(函数F(x,a)を区間[x0,x1]で積分する)
from scipy import integrate
integrate.quad(F,x0,x1,args=(a))[0]

◎重積分(函数F(y,x)を区間[y0=f0(x),y1=f1(x)],[x0,x1]で積分する(yを先に積分する)
 integrate.dblquad(F,x0,x1,lambda x:f0(x),lambda x:f1(x),args=(a,b))#よくわからんけどparameterは2つ以上ないと走らない

[特殊函数]
●ガンマ函数 Gamma(x)=>gamma(x)
from scipy.special import gamma
●第二種変形ベッセル函数 K_v(x)=>kv(v,x)
from scipy.special import kv
●ルジャンドル多項式
from scipy.special import legendre
legendre(n)#n次の多項式として使える

np.arrayあれこれ
import numpy as np
●同じ値だけのnpを作成(要素数:10)
np.zeros(10)#全て0
np.ones(10)#全て1
np.full(10,a)#全てa
●ある連続した要素数だけを抽出
X[:n]#0からnまで
X[n:]#nから最後まで
●順序の逆転
X[::-1]
●転置
X.T
●昇順にする(要検討)
np.sort(X)
●昇順にする(npのある要素にのみ注目する)
X=np.array([[1,9],[2,8],[3,7]])#でX[:1]に関して昇順にしたいとする
N=np.argsort(X[:,1])#X[:1]を昇順になるようにindexを入手
X2 = X[np.argsort(X[:,1])]
●結合
Z=np.append(X,Y)
●結合2A=([a0,a]とBC=[[b0,b1],[c0,c1]]みたいなのを結合する)
ABC=np.vstack(A,BC)#ABC=[[a0,a1],[b0,b1],[c0,c1]]みたいになるが怪しい?
●要素の和をとる
np.sum(X)
np.sum(X[0:i])#index 0-iまでの和
●2つのnpの各要素で大きい(小さい)方を取得する
X,Y:同じ長さのnp
np.maximum(X,Y)#X[i],Y[i]で大きい方がZ[i]となる
np.minimum(X,Y)#X[i],Y[i]で小さい方がZ[i]となる
●最大値/最小値
np.amax(X)
np.amin(X)
●最大/最小要素のindex
np.argmax(X)
np.argmin(X)
●極大/極小要素のindex(複数)
from scipy import signal
signal.argrelmax(X)
signal.argrelmin(X)
●ある条件を満たす要素だけを処理する
np.where((condition),X,Y)#X(Y):conditionを満たす(満たさない)要素への演算
X = np.linspace(0,10,11)
X_new = np.where(X>5,2*X,X/2)
※条件が複数のとき:and=>&,or=>|
◎要素の削除
 X=np.array([0,1,2,3])
 X_new=np.delete(X,0)#0行目が消える
◎要素の削除2
 X=np.array([0,1,2],[3,4,5],[6,7,8])#各々arrayとする
 X_new=np.delete(X,0,0)#とかで便利に消せる
●Ceck shape of X
print(X.shape)
●Reshape X=[1,2,3,4]=>Y=[[1,2],[3,4]]
Y=X.reshape(2,2)
●函数F(x)についてX(独立変数)を用いてF(X)を作成
Y=np.array([F(x) for x in X])
●分割(要検討)
np.array(np.array_split(X, M))#X=[MN個]=>X=[[N],[N],...M個]にする
●ある条件(F(x)>0)を満たす要素のみを抽出する
X,Y:同じ長さのnp
Y2 = Y[F(X)>0]#条件を満たすX[i]に対応したY[i]だけ抽出される

ファイルの操作
[読み込み]
●方法1(文字列がないとき)
X = []
with open("XXX.txt") as f:
 next(f)#ヘッダー(1行目)飛ばす
 for line in f:
  line = list(map(float,line.split()))
  X.append(line[0])

●方法2(文字列があるとき)
X=[]
with open("XXX.txt") as f:
 for line in f:
  name = line.split()[0]#1行目が天体名の設定
  del line[0]
  line = list(map.float,line.split())#以下同じ

●csvファイル読み込み
import csv
X = []
with open("XXX.csv") as f:
 reader = csv.reader(f)
 for line in reader:#以下textファイルと同じ

●csvファイル読み込み2(Pandaを使う)
import pandas as pd
Data = pd.read_csv("XXX.csv")
print(Data.keys())#ラベルを表示
Data1 = Data["1"].values#ラベル1に対応するデータをnpとして取得

[書き込み]
●方法1(最も簡単なもの)
data = np.array([X,Y,...]).T
np.savetxt("FILENAME.txt",data,fmt="%s")
●方法2(少し複雑なもの)
with open("FILENAME.txt","w") as f:#書き込み用file作成
 print("X,Y,...", file=f)#label的なやつ
 for i in range(len(X)):
  data = np.append(X[i],Y[i],...)
  print(*data,file=f)#*をつけると良い(なんでか忘れた)

統計
◎平均、中央値、(標本)分散、標準偏差
 import statistics as sta
 X=np.array([0,1,...])
 mean = sta.mean(X)
 median = sta.median(X)
 variance = sta.pvariance(X)
 standard_deviation = sta.pstdev(X)

◎パラメータ推定とその信頼区間(モデル関数F(x;a1,...,an)でデータ(xi,yi)をフィットし、パラメータの信頼区間を推定)
 def Error(var,*arg):###calcluate chi^2 for a given t0 (variable) and v (parameter)
  a1,...,an = var
  a0, www = arg #www is dammy
  Y = F(xi,a0,...,an)
  return np.sum(((yi-Y)/dyi)**2)

 def Error2(a0):#minimize chi^2 for a given a0
  bounds = ((a1_1,a1_2),...,(an_1,an_2))
  Para = scipy.optimize.brute(Error,ranges=bounds,args=(a0,0),Ns=20)
  return Error(Para,a0,0)-chi_min

 FUNC = lambda a0 : Error2(a0)-1 #dchi^2=1で63.8%の信頼区間を1parameterについて求める
 a0_error=optimize.brentq(FUNC, a0_best, a0_best + 0.1*np.abs(a0_best))
 a0_error2=optimize.brentq(FUNC, a0_best - 0.1*np.abs(a0_best), a0_best)

分岐/ループ
●分岐のバリエーション
if not X:#"Xでない"という条件が使える
●要素と要素数でループをまわす(array Xの要素xについて)
for i,x in enumerate(X):
●ループを後ろからまわす(array Xの要素xについて)
for x in reversed(X):
●複数の変数でループをまわす(array XとY [len(X)=len(Y)]について)
for x,y in zip(X,Y):

並列処理
●サンプル

スクリプトを書く
パラメータサーベイなどを行うときは長い計算やる前に動くことを確認すること
●基本
import subprocess
command = ["pyhton3","XXX.py"]
Input = "a\nb\n"#コードXXX.pyがinput a,bを必要とするとき
run = subprocess.run(command, input=Input,capture_output=True, text=True)#計算
print(ans.stdout)#これでXXX.pyの出力が全て出る

その他の便利な操作
●"nan"かどうかの判定(X = float("nan")として)
if X == X:#nanなら弾かれる
●多次元listのindexを取得する
X=[["A",2],["B",4],["C",6]]に対して"B"を含むlistのindexが知りたい
index = X.index(next(sublist for sublist in X if "B" in sublist))
(nextの使い方よくわからん)
◎変数の型を判定する
 isinsrance(X,float)#XがfloatならTrueを返す(分岐に使える)
◎数字を文字列に変換する
 ii = "%03d" % i#iを3桁の文字列iiに変換する(ファイルの操作に使える)
◎函数を簡略化して定義する
 F = lambda x,y:x**2+y**2
◎現在時刻を知る
 import datetime
 print(datetime.datetime.now())
◎複数のlistを同時にnp.arrayに変換
 X,Y,Z,...=map(np.array,[X,Y,Z,...])

[directory関係]
import os
●現在のdirを表示
print(os.getcwd())
●dirを絶対pathで移動
path = "XXX"
os.chdir(path)