tanakahdaのプログラマ手帳

プログラミングとかソフトウェア開発とかの備忘録

Python

pipで依存関係の問題を出力する@Python

pip check spyder 5.1.5 requires pyqt5, which is not installed. spyder 5.1.5 requires pyqtwebengine, which is not installed. daal4py 2021.3.0 requires daal, which is not installed. conda-repo-cli 1.0.4 requires pathlib, which is not install…

pandasでgroupby@Python

faq_datas = pd.read_csv('data/kansentaisakufaq20210315.csv', \ encoding = "shift-jis", header=None, skiprows=[0,1,2], names=['no', 'category1', 'category2', 'question', 'answer']) faq_datas faq_datas.groupby('category1').count()

import, from, as について@Python

bar.py def foo(): pass # importとは、別のファイル(モジュール)に記述されたPythonコードを読み込む import bar bar.foo() # モジュールの全体を利用するのが、importで、モジュールの一部の変数や関数を利用するのが、from from bar import foo foo() #…

テキスト読み込み@Python

レガシーな書き方 /data/data.txt Hello World! file = open("./data/data.txt") text = file.read() file.close() print(text) Hello World! with open()の書き方 # with open()構文でファイルを開くと、ファイルの入出力が、構文内だけで実行される # 明示…

リストの最も大きな値の要素番号を返す@Python

import numpy as np auc = [] auc.append(0.899) auc.append(0.883) auc.append(0.883) auc.append(0.993) auc.append(0.993) #同じ値がある場合は小さいほうの要素番号を返す np.argmax(auc) 3

テキストファイルを新規作成してテキストを書き込む@Python

path = 'sample.txt' s = '吾輩は猫である。\n名前はまだ無い。\nどこで生れたかとんと見当がつかぬ。' with open(path, mode='w') as f: f.write(s) # 書き込まれた内容を標準出力 with open(path) as f: print(f.read()) 吾輩は猫である。 名前はまだ無い…

pandas.Seriesで列追加し初期値を既存列の値を評価して代入@Python

既存列「score」の中央値を算出し、中央値より大きい場合は1、そうでない場合は0を初期値へ代入した「score_category」を追加 score_median = df.score.median() df['score_category'] = df['score'].map(lambda x: 1 if x > score_median else 0)

スライス機能を使って配列を削除@Python

# リスト[開始インデックス:終了インデックス] = [] # 0番目(cat)の位置から、2番目(lion)までをスライス(※lionは含まれない) animals = ['cat', 'dog', 'lion', 'monkey'] animals[0:2] = [] print(animals) # 1番目(dog)の位置から、3番目(monkey)までを…

PandasのDataFrameの初期化@Python

test_df = pd.DataFrame([['aaa',1],['bbb',2]], columns=['labels','value']) print(test_df)

sklearnのr2_scoreを使って決定係数を求める@Python

Yは実測値、Y_predictを予測値とした場合 from sklearn.metrics import r2_score print('R^2={:.3f}'.format(r2_score(Y, Y_predict)))

irisデータセットをseabornで散布図に展開し単回帰分析してみる@Python

irisデータセットを読み込む import pandas as pd import seaborn as sns df = sns.load_dataset('iris') df sepal length ... ガクの長さ sepal width ... ガクの幅 petal length ... 花弁の長さ petal width ... 花弁の幅 散布図に展開する 行データから花…

seabornでirisデータセットをPandasのDataFrameへ読み込む@Python

import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = sns.load_dataset('iris') df 参考: seabornをなぜ as snsとしてimportするのか - Qiita

Pandasである列を値ごとに集計する@Python

bank.job.value_counts() management 969 blue-collar 946 technician 768 admin. 478 services 417 retired 230 self-employed 183 entrepreneur 168 unemployed 128 housemaid 112 student 84 unknown 38 Name: job, dtype: int64 ちなみにある列の総数を…

フィボナッチ数列@Python

""" フィボナッチ級数を任意の上限まで書き出す関数 nまでのフィボナッチ級数を表示する """ def fib(n): a, b = 0, 1 while a < n: print(a, end=',') a, b = b, a + b fib(2000) 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597, 参考文献・引用:…

リストを数える@Python

ビルドイン関数len()で数える list = [1, 2, 3] len(list)

Listの追加@Python

list.append(4) list [1, 2, 3, 4]

リストの連結@Python

list = [1, 2, 3] list + [4, 5, 6] [1, 2, 3, 4, 5, 6]

文字列のインデックス指定@Python

文字列の自動的な連結@Python

列挙された文字列リテラル(引用符で囲まれたもの)は自動的に連結される

文字列を*演算子で繰り返し@Python

JupyterLabの事始め@Python

ANACONDAをインストールして、JupyterLabを起動する

proxy環境でpipを実行する@python

python -m pip install --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org pip --upgrade pip Collecting pip Downloading pip-20.3.1-py2.py3-none-any.whl (1.5 MB) |████████████████████████████████| 1.5…

os.listdir でディレクター一覧を取得してunicode変換

import osdirectory = os.listdir('/Users/tanakahda/Desktop/files')print directoryprint unicode(directory[0], 'utf8')

テキストの行数を数える@Python3

print (sum(1 for line in text))