by shigemk2

当面は技術的なことしか書かない

Python

DataFrame カラムだけ

pandas.DataFrame — pandas 0.23.4 documentation こういうふうにしてカラムだけ定義することができる。 pds = pd.DataFrame(columns=[ 'id', 'name' ])

Python round

組み込みです。roundです。小数点の精度の問題で、きちんと丸まらない可能性はあります。 Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. 2. 組み…

Python最新情報メモ

Pythonの最新情報メモ。RSSあり。 Python Insider

to_csv

DataFrameをcsvに pandas.DataFrame.to_csv — pandas 0.23.4 documentation

train_test_split

データを、テストデータと訓練データに分割 test_size テストデータの分割割合 だいたい2割-3割 train_size テストデータの分割割合 shuffle データ RandomState 乱数制御 sklearn.model_selection.train_test_split — scikit-learn 0.20.0 documentation

sqlparse 雑メモ

Python 2.7.14 日本語の含まれたクエリで、--reindent --keyword upper を標準出力実行してもOKだけど、ファイルにリダイレクトすると UnicodeEncodeError: 'ascii' codec can't encode characters in position で死ぬ

read_csv

read_csvがあるならto_csvもある pandasでcsv/tsvファイルの読み書き | mwSoft いちおうエンコードのデフォルトは、utf-8らしい pandas.DataFrame.to_csv — pandas 0.23.4 documentation

trollius

お許しください 2的な書き方です。3以降は別の書き方になります pip install trollius みたいなのもひつようないです import trollius as asyncio from trollius import From @asyncio.coroutine def loop_array(name, array): for i in array: print("Task …

matplotlib tutorial

matplotlib tutorial #coding: utf-8 import matplotlib.pyplot as plt # plt.plot([1, 2, 3, 4]) #なだらか # plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) #(1,1)(2,4)(3,9)(4,16) plt.plot([1, 2], [3, 4], [1, 4], [9, 16]) #なんかよくわからない plt.ylabel…

pyguide

pyguide 検索上位がDeprecatedなものであるという https://google.github.io/styleguide/pyguide.html どうでもいいけどTensorflowのPythonのインデントはスペース2なんだね

numpy argmax

argmaxで、最大値のインデックスをとる >>> import numpy as np >>> a = np.array([1,2,3,4,5]) >>> np.argmax(a) 4 最大値な値が複数あったら、最初のインデックスをとる >>> b = np.array([3,3,1,2,0]) >>> np.argmax(b) 0 numpy.argmax — NumPy v1.15 Man…

google spreadsheet api

google spreadsheet api なのだけど、updateは既にセルにデータが入っていたら何もしない挙動になっている https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append https://developers.google.com/sheets/api/reference/re…

Python flatten

>>> import operator >>> l = [[1,2,3],[4,5,6], [7], [8,9]] >>> reduce(operator.concat, l) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> l [[1, 2, 3], [4, 5, 6], [7], [8, 9]] >>> reduce(operator.add, l) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reduce(lambda x, y: …

numpy 1.15.0

Python3.4が1.16で、2.7が1.17でサポート終了とな Release v1.15.0 · numpy/numpy · GitHub

pyenvとpipとFrameworkビルド

matplotlibを使いたいがためにpyenvでFrameworkビルドなPythonをインストールする なぜかpipが入っていない 公式からpipのインストールを試みるもインストールパスを指定する方法がわからずめんどくさいからpipだけ/home/.pyenv/shimsにcp

RssLibraries

import feedparser python_wiki_rss_url = "http://www.python.org/cgi-bin/moinmoin/RecentChanges?action=rss_rc" feed = feedparser.parse( python_wiki_rss_url ) print(feed) ↓のリンク参照 https://wiki.python.org/moin/RssLibraries

beautifulsoup findAll

要素を配列に突っ込みながら、Lambdaでフィルタリングもできる soup.findAll(text="one") # [u'one'] soup.findAll(text=u'one') # [u'one'] soup.findAll(text=["one", "two"]) # [u'one', u'two'] soup.findAll(text=re.compile("paragraph")) # [u'This i…

Google Spreadsheets

Google SpreadsheetsのPython Quickstart の最新 store = file.Storage('token.json') がうまく読み込めないのでNoneにした https://developers.google.com/sheets/api/quickstart/python

import re

import re は一応書かないといけない https://docs.python.org/2/library/re.html

BeautifulSoup

BeautifulSoup スクレイピングのアレ。 pip install bs4 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#

Python json

import json が決め手のおまじない loads デコード dumps エンコード https://docs.python.jp/3/library/json.html

numpy.random.shuffle

配列の中身を破壊的にシャッフル https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html

genfromtxt

genfromtxtで、カラム数1のデータをgenfromtxtすると、多次元配列にならない >>> import numpy as np >>> from StringIO import StringIO >>> data = "1, 2, 3\n4, 5, 6" >>> np.genfromtxt(StringIO(data), delimiter=",") array([[1., 2., 3.], [4., 5., 6…

PyCharmでvirtualenvを使うメモ

PyCharmでvirtualenvを使うメモ デフォルトだとパスの通ったPythonを使うので、virtualenvを使うには別途設定が必要 environment location dirctoryは空じゃないとダメ https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html

matplotlibをpyenvで使おうとしたときのRuntimeError

Python 2.7.11(pyenv) matplotlib 2.2.2 import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] plt.plot(x, y) plt.show() 無邪気にpyenvでmatplotlibを動かそうとしたら、以下のようなエラーに見舞われた。 RuntimeError: Python is n…

python-redmine

RedmineをPythonでごにょごにょするやつ https://python-redmine.com/introduction.html

Python unicodeな文字列でreplaceとかformatとかやったときの挙動

unicodeな文字列でreplaceとかformatとかやったときの挙動 >>> a = "日本語".decode("utf-8") >>> a u'\u65e5\u672c\u8a9e' >>> b = "{}".format(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't enco</module></stdin>…

Python KeyError in format

ソースコードを追っかけても原因がよくわからなかったけどドキュメントを読んだらなんとなくわかった >>> a = "{} {'alpha': 1234, 'omega': 5678}".format("test") Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: "'alpha'" >>> a = "</module></stdin>…

python-slackclient

PythonでSlackをごにょごにょするやつ from slackclient import SlackClient slack_token = os.environ["SLACK_API_TOKEN"] sc = SlackClient(slack_token) sc.api_call( "chat.postMessage", channel="C0XXXXXX", text="Hello from Python! :tada:" ) APIト…

pykakasi

Cのライブラリ kakasiの再実装 漢字カタカナひらがなをローマ字に変換する