【Python】 pythonからshellの実行
Pythonからshellコマンドを実行する際に以下のようなやり方がある.
今回は次のshellコマンドをpythonで実行するやり方を比較する.
$sha256sum hoge.zip #返り値: xxxxxxxxxxx hoge.zip
os.system()を使う方法
import os file_name = "hoge.zip" os.system('sha256sum "{}"'.format(file_name)) # 成功 # xxxxxxxxxxx hoge.zip # 0 # 失敗 # sha256sum: hoge.zip : No such file or directory # 256
成功したか失敗したかのみしかわからない.
コマンドの出力が受け取れないし, 推奨されていないやり方らしい.
subprocess.check_output()を使う方法
import subprocess file_name = "hoge.zip" args = ["sha256sum", file_name] subprocess.check_output(args) # 成功 # b'16e3a87f14dce201f90dc0f7dd2a6318e7b9e5aef095e5815123c3a44e92ac97 GA_result.txt\n' # 失敗 # sha256sum: hoge.zip : No such file or directory #Traceback (most recent call last): # File "<stdin>", line 1, in <module> # File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 316, in check_output **kwargs).stdout # File ".pyenv/versions/3.5.4/lib/python3.5/subprocess.py", line 398, in run output=stdout, stderr=stderr) # subprocess.CalledProcessError: Command '['sha256sum', 'GA_result1.txt']' returned non-zero exit status 1
成功した場合, 返り値はbyte型なのでstr型にdecodeし, pythonコード内でshellの出力結果を得ることができる.
res = subprocess.check_output(args) hash_value = res.decode("utf-8").split(" ")[0]
ただし, windowsの場合はうまく行かない可能性がある. 原因はまだ良く見てない.
commands.getstatusoutput()を使う方法
昔よく使っていたが, Python3 で廃止されたらしい.
これの代用がsubprocessモジュールになったらしい.
【TeX】 ページを跨いで表を表示する
longtable.styを使う
\newcolumntype{A}{>{\raggedright}p{0.3cm}} \newcolumntype{N}{>{\raggedright}p{3.6cm}} \newcolumntype{D}{>{\raggedright}p{10.0cm}} {\footnotesize \begin{longtable}[c]{|A|N|D|} \hline No & permission-name & Description \tabularnewline \hline \endfirsthead 0 & \verb|ACCESS_CHECKIN_PROPERTIES| & Allows read/write access to the "properties" table in the checkin database, to change values that get uploaded.\tabularnewline \hline 1 & \verb|ACCESS_COARSE_LOCATION| & Allows an app to access approximate location. \tabularnewline \hline 2 & \verb|ACCESS_FINE_LOCATION| & Allows an app to access precise location.\tabularnewline \hline 3 & \verb|ACCESS_LOCATION_|\\ \verb|EXTRA_COMMANDS| & Allows an application to access extra location provider commands. \tabularnewline \hline \end{longtable} }
【参考】
・http://www.biwako.shiga-u.ac.jp/sensei/kumazawa/tex/longtable.html
・https://ctan.org/pkg/longtable
【Python】 再帰的にファイルを取得する
import os def find_all_files(directory): for root, dirs, files in os.walk(directory): #yield root # ここをアンコメントするとディレクトリも得られる for file in files: yield os.path.join(root, file) if __name__ == "__main__": path_directory = "SAMPLE" for file in find_all_files(path_directory): print(file)
treeコマンドのようにファイルを取得できる.
os.walk()とos.path.join()は始めて知った.
os.path.join(path_directory, name_file)でpath_directory + "/" + name_fileとしてくれるようだ.
普段
path ="aaaa" for file in os.listdir(path): path_file = path + "/" + file
とファイルのpathを取得していたためこれは少し感動.
さらにwindowsとlinuxの"\\"と"/"の違いも一々気にする必要なさそうで便利!
【Python】 confusion_matrtixの作り方
seabornのheatmapによって表現できる.
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # scikit-learnのconfusion_matrixクラスで b = np.array([[251, 22, 1, 3, 0, 1, 3, 16, 24], [ 8, 459, 0, 2, 0, 1, 0, 4, 23], [ 0, 1, 557, 0, 0, 0, 0, 1, 0], [ 0, 3, 0, 90, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 1, 0, 0, 4, 0], [ 35, 20, 1, 8, 0, 50, 0, 7, 31], [ 0, 3, 0, 5, 0, 0, 78, 0, 0], [ 11, 1, 4, 9, 0, 1, 0, 228, 1], [ 34, 39, 0, 0, 0, 2, 0, 11, 119]]) labels = ["a","b","c","d","e","f","g","h","i"] #pandas.dataframeに格納 b = pd.DataFrame(b,index=labels,columns=index) sns.heatmap(b,annot=True,cmap="Reds") plt.show()
【データ分析】 特徴量の相関関係の図の見方
図[2][4]は正の相関関係があるとわかる.
図[1][1]は緑と赤の分布がほぼ同じであり, 分離が厳しいことがわかる. 図[0][1]でも混じっている.
これを処理するためには, SepalWidthCm特徴量を削除したり工夫する必要がある.
【pandas】 DataFrameの操作について
Irisで試す
# データCSVの読み込み iris = pd.read_csv("input.csv")
# データのある特徴列を削除する iris.drop("Id", axis=1, inplace=True)
# 同データのカウント # ”Species”という特徴列の名義特徴量の種類をそれぞれカウント iris["Species"].value_counts()
# 各特徴列の値の個数をカウント # null値があるかもチェック # memoryなども表示してくれる iris.info()
# count, mean, std, min, 25, 50, 75, maxを算出
iris.describe()
【Python】 Jupyter notebookで実行に影響のない警告は無視する
warning.filterwarning("ignore")により警告を無視して進めることができる.
import warnings warning.filterwarnings("ignore")
【seaborn】 plotについて
seabornライブラリでデータを可視化したい場合, BoxplotとViolinplotなどがある.
ラベルAとラベルBの正規化, 標準化済の特徴量3つをとってきて比較することに用いられる.
Boxplotでは下図のような図をプロットでき, 中央値などがわかりやすい.
(図引用: https://qiita.com/TomHortons/items/5b585a6860ff5ccd5ba5)
Violinplotでは下図のように分布の形や, 多峰性を確認しやすい.
【参考】
・https://qiita.com/TomHortons/items/5b585a6860ff5ccd5ba5
【pandas】 DataFrame.iloc
DataFrameに対して列番号を指定する.
【pandas】 DataFrameに辞書形式で格納する
>>> pd.DataFrame({"feature1":[1,2,3],"feature2":[0.1,0.2,0.3]}) feature1 feature2 0 1 0.1 1 2 0.2 2 3 0.3
【参考】
・【pandas】 CSVの読み込み - メモ的な何か
・https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html
【pandas】 DataFrame.describe()について
DataFrame.describe()はDataFrameに格納されているそれぞれの特徴量(横軸)に対して
数値データならcount, mean, std, min, 25%, 50%, 75%, maxを計算,
カテゴリデータならcount, unique(カテゴリの種類), top(先頭), freq(最頻値)を計算してくれる便利な機能
【参考】
・https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html
【pandas】 CSVの読み込み
csvファイルをpandas.DataFrameに格納する方法
# 読み込み csv_path = "./data.csv" data = pd.read_csv(csv_path) # データの表示(Jupyter notebookなどで) # .head()メソッドを使えば,先頭から5行が表示される data.head() # 特徴量の名前をリストとして取得する(特徴量は基本的に横軸にセットされる) # インスタンス変数columnsとして取得できる col = data.columns # データフレームの特徴量の一つを抽出(ラベルなど) # 特徴量の名前"name_of_feature"に対して y = data.name_of_feature
【Linux】 gifファイルを圧縮
gifsicle -i < hoge.gif > fuga.gif