サクサク読めて、アプリ限定の機能も多数!
トップへ戻る
ノーベル賞
python-remrin.hatenadiary.jp
ニュートン法で平方根を求める。 ・まずは√2 def a(x): return (x**2 + 2) / (2 * x) x = 2 # 初期値(0以外の値) for i in range(6): x = a(x) print(x) # 1.5 # 1.4166666666666667 # 1.4142156862745099 # 1.4142135623746899 # 1.414213562373095 # 1.414213562373095 ニュートン法は接線を利用することで解の近似を行っている。 続いて√3 def a(x): return (x**2 + 3) / (2 * x) x = 2 # 初期値(0以外の値) for i in range(8): x = a(x) print(x) # 1.75 # 1.7321428571428572 # 1.7320508100147
matplotlibで図形を描く方法。 plot()関数が呼ばれると背後でfigure()が呼ばれ、続いてaxes()が呼ばれてfigureの中に軸をつくる。 plot()関数を呼ばずにfigure()やaxes()で図、軸を設定できる。 import matplotlib.pyplot as plt c1 = plt.Circle((0, 0), radius=1, fc="yellow", ec="r") ax = plt.gca() ax.add_patch(c1) plt.axis("scaled") plt.show() ○figure()関数 Figureオブジェクトを作る。 Definition : figure(num=None, # autoincrement if None, else integer from 1-N figsize=None, # defaults
乱数を発生させるライブラリは主に2つ。 randomライブラリとNumPyのrandom 2つのライブラリの一番の違いは乱数の発生個数。 乱数の発生個数 randomモジュール :乱数1個 numpyは配列の形をsize=~の形のキーワード引数で乱数の個数を指定できる。 size 省略 →1個の乱数 size = 数値 →1次元配列 size = タプル→多次元配列 乱数の初期化 random.seed(数値) np.random.seed(数値) 同じ初期値にすると、再現性のある乱数列になる。 小数(一様uniform) 0~1の乱数 random.random() 0~1の乱数乱数を1個生成。 np.random.rand(size) 0~1の乱数列。配列生成後に再計算すると範囲を変えられる 範囲を指定した乱数 random.uniform(low, high) low以上high未
ベクトル演算とユニバーサル関数について。 ベクトル演算 ndarrayと数値(スカラー)の計算は全要素対象で、forループを使わない。 ndarrayどうしの演算は対応する位置の要素どうしで計算。 [注意]ndarray * ndarrayは内積や外積にはならない。 import numpy as np a1 = np.arange(6).reshape(2, 3) print(a1) # [[0 1 2] # [3 4 5] print(a1 + 1) # [[1 2 3] # [4 5 6] print(a1 - 1) # [[-1 0 1] # [ 2 3 4] print(a1 * 2) # [[ 0 2 4] # [ 6 8 10] print(a1 / 10) # [[ 0. 0.1 0.2] # [ 0.3 0.4 0.5] print(a1 ** 2) # [[ 0 1 4
matplotlibのグラフの設定について 日本語の表示 日本語を表示する場合は、表示するごとにfontproperties = fpをセットする。 from matplotlib.font_manager import FontProperties fp = FontProperties(fname='C:\WINDOWS\Fonts\msgothic.ttc', size=14) plt.title("折れ線グラフ", fontproperties=fp) グラフのタイトル plt.title(str, loc='center') ・表示位置 loc='center' 中央。デフォルト loc='left' 左寄せ loc='right' 右寄せ 表示範囲(変域) ・両軸の表示範囲の取得 xmin, xmax, ymin, ymax = plt.axis() ・両軸の表示範囲の設定 p
データフレームを作る(1) numpyの配列から作る。 import numpy as np import pandas as pd a = np.random.randint(1, 100, (3, 2)) frame = pd.DataFrame(a, columns=["a", "b"]) print(frame) # a b # 0 85 80 # 1 85 10 # 2 17 38 データフレームを作る(2)リストから import numpy as np import pandas as pd d =[[1, 2, 3], [50, 60, 70]] frame = pd.DataFrame(d) print(frame) # 0 1 2 # 0 1 2 3 # 1 50 60 70 print(frame.T) # 0 1 # 0 1 50 # 1 2 60 #2 3 70
htmlの構文解釈のライブラリです。 ○htmlの準備 # -*- coding: utf-8 -*- import urllib.request from bs4 import BeautifulSoup url = "http://python-remrin.hatenadiary.jp/" f = urllib.request.urlopen(url) html = f.read().decode('utf-8') soup = BeautifulSoup(html, "html.parser") ○タイトルの表示 title タグ+文字 title.name タグのみ title.string 文字のみ print(soup.title) #<title>Remrinのpython攻略日記</title> print(soup.title.name) #title print(so
Numpyの配列の結合・分割について。 np.concatenate() 2個以上の配列を軸指定して結合する。 軸指定オプションのaxisはデフォルトが0 マスクは保存されない。(マスクについては別の記事で) import numpy as np a1 = np.array([[1, 2, 3], [4, 5, 6]]) a2 = np.array([[7, 8, 9], [0, 11, 12]]) print(np.concatenate([a1, a2], axis=0)) # [[ 1 2 3] # [ 4 5 6] # [ 7 8 9] # [ 10 11 12]] print(np.concatenate([a1, a2], axis=1)) # [[ 1 2 3 7 8 9] # [ 4 5 6 10 11 12]] ・軸axisの指定はすでに存在している軸のみ。 (Join
pythonでファイルの読み書きです。 python3で外部ファイルを開くときはcodecsモジュールは不要です。 パスが通ったディレクトリにhyaku.txtがあることを前提にしています。 なければ、メモ帳などで適当に複数行の文字を書き込んだりで。 今回は百人一首を書き込んだテキストファイルを準備しました。 # coding: utf-8 #テキストファイルの読み込み with open("hyaku.txt", "r") as f: # txt形式の読み込み data = f.read() # ひとまとまりのデータとして読み込む data = data.split("\n") # 改行コードで1行ずつに分割 print(data) # 'あきのたの... と100行分表示 print(len(data)) # 100 #テキストファイルへの書き込み(上書き) text = "\n".j
PIL(Python Imaging Library)の使い方について。 画像の読み込み img = Image.open("filepass") のように、ファイルを読み込む。 この時点では参照されているだけで、必要になってからデータを読み込む。 下の例では作業ディレクトリの下のdataフォルダに該当ファイルがなければ FileNotFoundError: [Errno 2] No such file or directory: 'data/img01.png' というエラーが出る。 from PIL import Image # 画像を読み込む img = Image.open( "data/img01.png" ) print(type(img)) # <class 'PIL.PngImagePlugin.PngImageFile'> print(img.size) # (320,
このページを最初にブックマークしてみませんか?
『Remrinのpython攻略日記』の新着エントリーを見る
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く