Python/TIPS集
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
単語検索
|
最終更新
|
ヘルプ
|
ログイン
]
開始行:
#topicpath
----
#contents
*** NumPyでfor文 [#y9ec1cca]
[print(y[i]) for i in range(y.shape[0])]
遅いからあんまりよろしくないみたいですね
*** 配列データを追加する [#rd087b93]
>>> import numpy as np
>>> a = np.empty((0,10))
>>> a
array([], shape=(0, 10), dtype=float64)
>>> a = np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8,...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8,...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>>
*** データ列をくっつける、分割する。 [#q3d0f8de]
https://note.nkmk.me/python-numpy-split/
>>> import numpy as np
>>> data_size = 10
>>> x = np.random.choice(data_size,10,replace = False)
>>> x
array([8, 6, 1, 5, 2, 7, 9, 4, 0, 3])
>>> f = lambda x: x**2.0
>>> y = f(x)
>>> y
array([64., 36., 1., 25., 4., 49., 81., 16., 0., 9.])
>>> np.stack([x,y],axis=1)
array([[ 8., 64.],
[ 6., 36.],
[ 1., 1.],
[ 5., 25.],
[ 2., 4.],
[ 7., 49.],
[ 9., 81.],
[ 4., 16.],
[ 0., 0.],
[ 3., 9.]])
>>> np.stack([x,y])
array([[ 8., 6., 1., 5., 2., 7., 9., 4., 0., 3.],
[64., 36., 1., 25., 4., 49., 81., 16., 0., 9....
>>>
分割は、
>>> X,Y=np.split(z,2,axis=1)
>>> X
array([[8.],
[6.],
[1.],
[5.],
[2.],
[7.],
[9.],
[4.],
[0.],
[3.]])
>>> Y
array([[64.],
[36.],
[ 1.],
[25.],
[ 4.],
[49.],
[81.],
[16.],
[ 0.],
[ 9.]])
>>>
*** 切り捨て除算 [#gfbf05b2]
>>> 20 / 3
6.666666666666667
>>> 20.0 / 3.0
6.666666666666667
>>> 20.0 // 3.0
6.0
>>> 20 // 3
6
>>>
***HTTP(s)リクエストで、プロキシを通す件 [#yde6d6c1]
proxies = {
"http": "http://username:password@proxy:8888",
"https": "http://username:password@proxy:8888"
}
r = requests.post(
'https://labs.goo.ne.jp/api/morph',
data=payload.encode('utf-8').decode('latin-1'),
headers=headers,
proxies=proxies,
verify=False)
などでOK。SSLのチェックはverify=FalseでOFFにしている。ま...
-[[認証プロキシ環境でpythonのRequestsライブラリを使用する...
-[[ssl - Python Requests throwing SSLError - Stack Overfl...
*** 複数の戻り値を返す件。 [#m889e777]
[[Pythonの関数で複数の戻り値を返す方法 | note.nkmk.me>htt...
タプル型というので返すと、複数の戻り値を返せる。コレめっ...
*** クラスのメンバ変数にはアンスコを二つつける件 [#s422fb...
[[9. クラス ― Python 2.7.14 ドキュメント>https://docs.pyt...
***printf の書式設定 [#a5040a3d]
printf("Switchの状態:{0}".format(isClick)) #formatの第一...
printf("Counter: [{0:3.1f}]".format(counter/interval)) #...
って感じに文字列のformat関数というのでフォーマット可能。
[[Python3におけるformat形式を自分のためにまとめてみた件 -...
***Pythonでsubstring [#o419a869]
key = 'temperature_130010.json'
city_code = key[len('temperature_'):-5]
-> 130010
*** 設定ファイルをあつかう [#w677f138]
[[設定ファイル (ConfigParser) - Python入門から応用までの...
詳しく書いてあります。。
*** Javaのlongの日付をあつかう [#te897e89]
long dateLong = 1480232552192L;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:s...
Date date = new Date(dateLong);
System.out.println(df.format(date));
System.out.println(date.getTime());
実行結果
2016/11/27 16:42:32.192
1480232552192
from datetime import datetime
print(datetime.fromtimestamp(1480232552192/1000.0))
実行結果
$ python my_aws_utils.py
2016-11-27 16:42:32.192000
*** requirements.txt を使って複数ライブラリをインストール...
$ cat requirements.txt
requests
pytz
$ sudo pip3 install -r requirements.txt -t ./ ←(も...
Downloading/unpacking requests (from -r requirements.txt...
Downloading requests-2.12.1-py2.py3-none-any.whl (574k...
Downloading/unpacking pytz (from -r requirements.txt (li...
Downloading pytz-2016.7-py2.py3-none-any.whl (480kB): ...
Installing collected packages: requests, pytz
Successfully installed requests pytz
Cleaning up...
$ ls -lrt
合計 80
.....
-rw-r--r-- 1 pi pi 14 11月 21 23:56 requirements.txt
drwxr-xr-x 4 root root 4096 11月 21 23:57 requests
drwxr-xr-x 2 root root 4096 11月 21 23:57 requests-2.12....
drwxr-xr-x 4 root root 4096 11月 21 23:57 pytz
drwxr-xr-x 2 root root 4096 11月 21 23:57 pytz-2016.7.di...
$
ちなみに awsにアップするzipを作る際は、このディレクトリに...
$ zip -r xxx.zip ./*
でよいと思います。
-[[Python Tips:ライブラリをまとめてインストールしたい - ...
*** 添え字付きの for 文の文法 [#ze54935d]
returnList = []
codes = createCityCodes() ← 配列がふたつあったばあい、
names = createCityNames() ← こちらはnames[i]とかでアク...
for i,code in enumerate(codes):
returnObj = {
'cityCode': code,
'cityName': names[i]
}
returnList.append(returnObj)
みたいな感じに扱える。もしくは、
import itertools
.....
for code,name in itertools.zip_longest(codes,names):
returnObj = {
'cityCode': code,
'cityName': name
}
returnList.append(returnObj)
こんな感じで、複数の配列をおなじfor文で回すことも可能((py...
***改行をそのまま文字列であつかいたい [#te4d69fb]
「"""」や「'''」で始めて終わることで、その間の文字列はそ...
text1 ="""1行目
2行目
3行目"""
text2 ="""1行目
2行目
3行目"""
print ("----")
print (text1)
print ("----")
print (text2)
print ("----")
結果は
----
1行目
2行目
3行目
----
1行目
2行目
3行目
----
このとおり。文字列内の改行はそのまま改行と解釈され、さら...
'''
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliate...
.....
*/
'''
こんな感じで。なるほどね。。
***finallyがよばれない?? [#zbe6d819]
Linux上で、sudo kill した場合、try/finallyのfinallyがよば...
import sys,signalしといて
def cleanup(*args):
sys.exit(0)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
とか書いておくと、よばれるようになりますが、コレでいいの...
***他ファイルのメソッド呼び出し [#jb7fd7e3]
myutils.py に定義された
def cleanup(xx):
などのメソッドを呼び出すには、呼び出し側で
from myutils import cleanup,sysout
と宣言しておけば、
cleanup("hoge")
などと直接呼び出せる。
***public static void main ぽく書きたい [#df1b09f6]
PythonにはJavaでいう
public static void main(String[] args){
...
}
みたいな概念がなく、
sudo python3 xxx.py
と呼び出すと、先頭から順次実行されるっぽい。
いわゆるmainメソッドを作るやり方は以下の通りです。
import sys
def main(args):
メイン処理
if __name__ == "__main__":
main(sys.argv)
「 __name__ 」 には、スクリプトとして直接呼び出されたとき...
参考
-[[基本構文 - Python入門から応用までの学習サイト>http://w...
***MacでPython3 [#c8efcb87]
Yosemiteを使ってるとバージョンが2.7系で、、3.x系を使いた...
-[[pyenvとvirtualenvで環境構築 - Qiita>http://qiita.com/K...
-[[OSXでpyenvインストールメモ - Qiita>http://qiita.com/ry...
などを参考に、Python環境を管理するツールを入れます
$ brew install pyenv
$ echo 'export PYENV_ROOT=$HOME/.pyenv' >> ~/.bash_profile
$ echo 'export PATH=$PYENV_ROOT/bin:$PATH' >> ~/.bash_pr...
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
$ pyenv install 3.5.1
なんかエラーが出たら、たいがい
$ xcode-select --install
これもしくは、
$ sudo installer -pkg /Library/Developer/CommandLineTool...
(これはmojaveのばあい)
$ pyenv shell 3.5.1
$ python --version
Python 3.5.1
$
$ pyenv versions <-インストールされているモノの一覧。
* system (set by /Users/xxxx/.pyenv/version)
2.7.11
2.7.12
3.5.1
$
[[pyenvが必要かどうかフローチャート - Qiita>http://qiita....
***JSON文字列のDump [#s2abf34e]
r = requests.get('https://xxx/yyy.json')
result = json.dumps(r.json(),ensure_ascii=False, indent=...
print(result)
requests は pip(かpip3)などでインストールされてる前提で。。
[[[Python] JSONを扱う - YoheiM .NET>http://www.yoheim.net...
**関連リンク [#ke758226]
-[[[Python] 何度も調べてしまうリスト操作をまとめてみた - ...
-[[Python Tips:ライブラリをまとめてインストールしたい - ...
-[[Python の datetime オブジェクトと Unix 時間の相互変換...
-[[Python 3 で少しだけ便利になった datetime の新機能 - Qi...
----
この記事は
#vote(おもしろかった[2],そうでもない[0])
#comment
#topicpath
SIZE(10){現在のアクセス:&counter;}
終了行:
#topicpath
----
#contents
*** NumPyでfor文 [#y9ec1cca]
[print(y[i]) for i in range(y.shape[0])]
遅いからあんまりよろしくないみたいですね
*** 配列データを追加する [#rd087b93]
>>> import numpy as np
>>> a = np.empty((0,10))
>>> a
array([], shape=(0, 10), dtype=float64)
>>> a = np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8,...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>> a= np.append(a,[ [0, 1, 2, 3, 4, 5, 6, 7, 8,...
>>> a
array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.],
[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]])
>>>
*** データ列をくっつける、分割する。 [#q3d0f8de]
https://note.nkmk.me/python-numpy-split/
>>> import numpy as np
>>> data_size = 10
>>> x = np.random.choice(data_size,10,replace = False)
>>> x
array([8, 6, 1, 5, 2, 7, 9, 4, 0, 3])
>>> f = lambda x: x**2.0
>>> y = f(x)
>>> y
array([64., 36., 1., 25., 4., 49., 81., 16., 0., 9.])
>>> np.stack([x,y],axis=1)
array([[ 8., 64.],
[ 6., 36.],
[ 1., 1.],
[ 5., 25.],
[ 2., 4.],
[ 7., 49.],
[ 9., 81.],
[ 4., 16.],
[ 0., 0.],
[ 3., 9.]])
>>> np.stack([x,y])
array([[ 8., 6., 1., 5., 2., 7., 9., 4., 0., 3.],
[64., 36., 1., 25., 4., 49., 81., 16., 0., 9....
>>>
分割は、
>>> X,Y=np.split(z,2,axis=1)
>>> X
array([[8.],
[6.],
[1.],
[5.],
[2.],
[7.],
[9.],
[4.],
[0.],
[3.]])
>>> Y
array([[64.],
[36.],
[ 1.],
[25.],
[ 4.],
[49.],
[81.],
[16.],
[ 0.],
[ 9.]])
>>>
*** 切り捨て除算 [#gfbf05b2]
>>> 20 / 3
6.666666666666667
>>> 20.0 / 3.0
6.666666666666667
>>> 20.0 // 3.0
6.0
>>> 20 // 3
6
>>>
***HTTP(s)リクエストで、プロキシを通す件 [#yde6d6c1]
proxies = {
"http": "http://username:password@proxy:8888",
"https": "http://username:password@proxy:8888"
}
r = requests.post(
'https://labs.goo.ne.jp/api/morph',
data=payload.encode('utf-8').decode('latin-1'),
headers=headers,
proxies=proxies,
verify=False)
などでOK。SSLのチェックはverify=FalseでOFFにしている。ま...
-[[認証プロキシ環境でpythonのRequestsライブラリを使用する...
-[[ssl - Python Requests throwing SSLError - Stack Overfl...
*** 複数の戻り値を返す件。 [#m889e777]
[[Pythonの関数で複数の戻り値を返す方法 | note.nkmk.me>htt...
タプル型というので返すと、複数の戻り値を返せる。コレめっ...
*** クラスのメンバ変数にはアンスコを二つつける件 [#s422fb...
[[9. クラス ― Python 2.7.14 ドキュメント>https://docs.pyt...
***printf の書式設定 [#a5040a3d]
printf("Switchの状態:{0}".format(isClick)) #formatの第一...
printf("Counter: [{0:3.1f}]".format(counter/interval)) #...
って感じに文字列のformat関数というのでフォーマット可能。
[[Python3におけるformat形式を自分のためにまとめてみた件 -...
***Pythonでsubstring [#o419a869]
key = 'temperature_130010.json'
city_code = key[len('temperature_'):-5]
-> 130010
*** 設定ファイルをあつかう [#w677f138]
[[設定ファイル (ConfigParser) - Python入門から応用までの...
詳しく書いてあります。。
*** Javaのlongの日付をあつかう [#te897e89]
long dateLong = 1480232552192L;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:s...
Date date = new Date(dateLong);
System.out.println(df.format(date));
System.out.println(date.getTime());
実行結果
2016/11/27 16:42:32.192
1480232552192
from datetime import datetime
print(datetime.fromtimestamp(1480232552192/1000.0))
実行結果
$ python my_aws_utils.py
2016-11-27 16:42:32.192000
*** requirements.txt を使って複数ライブラリをインストール...
$ cat requirements.txt
requests
pytz
$ sudo pip3 install -r requirements.txt -t ./ ←(も...
Downloading/unpacking requests (from -r requirements.txt...
Downloading requests-2.12.1-py2.py3-none-any.whl (574k...
Downloading/unpacking pytz (from -r requirements.txt (li...
Downloading pytz-2016.7-py2.py3-none-any.whl (480kB): ...
Installing collected packages: requests, pytz
Successfully installed requests pytz
Cleaning up...
$ ls -lrt
合計 80
.....
-rw-r--r-- 1 pi pi 14 11月 21 23:56 requirements.txt
drwxr-xr-x 4 root root 4096 11月 21 23:57 requests
drwxr-xr-x 2 root root 4096 11月 21 23:57 requests-2.12....
drwxr-xr-x 4 root root 4096 11月 21 23:57 pytz
drwxr-xr-x 2 root root 4096 11月 21 23:57 pytz-2016.7.di...
$
ちなみに awsにアップするzipを作る際は、このディレクトリに...
$ zip -r xxx.zip ./*
でよいと思います。
-[[Python Tips:ライブラリをまとめてインストールしたい - ...
*** 添え字付きの for 文の文法 [#ze54935d]
returnList = []
codes = createCityCodes() ← 配列がふたつあったばあい、
names = createCityNames() ← こちらはnames[i]とかでアク...
for i,code in enumerate(codes):
returnObj = {
'cityCode': code,
'cityName': names[i]
}
returnList.append(returnObj)
みたいな感じに扱える。もしくは、
import itertools
.....
for code,name in itertools.zip_longest(codes,names):
returnObj = {
'cityCode': code,
'cityName': name
}
returnList.append(returnObj)
こんな感じで、複数の配列をおなじfor文で回すことも可能((py...
***改行をそのまま文字列であつかいたい [#te4d69fb]
「"""」や「'''」で始めて終わることで、その間の文字列はそ...
text1 ="""1行目
2行目
3行目"""
text2 ="""1行目
2行目
3行目"""
print ("----")
print (text1)
print ("----")
print (text2)
print ("----")
結果は
----
1行目
2行目
3行目
----
1行目
2行目
3行目
----
このとおり。文字列内の改行はそのまま改行と解釈され、さら...
'''
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliate...
.....
*/
'''
こんな感じで。なるほどね。。
***finallyがよばれない?? [#zbe6d819]
Linux上で、sudo kill した場合、try/finallyのfinallyがよば...
import sys,signalしといて
def cleanup(*args):
sys.exit(0)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
とか書いておくと、よばれるようになりますが、コレでいいの...
***他ファイルのメソッド呼び出し [#jb7fd7e3]
myutils.py に定義された
def cleanup(xx):
などのメソッドを呼び出すには、呼び出し側で
from myutils import cleanup,sysout
と宣言しておけば、
cleanup("hoge")
などと直接呼び出せる。
***public static void main ぽく書きたい [#df1b09f6]
PythonにはJavaでいう
public static void main(String[] args){
...
}
みたいな概念がなく、
sudo python3 xxx.py
と呼び出すと、先頭から順次実行されるっぽい。
いわゆるmainメソッドを作るやり方は以下の通りです。
import sys
def main(args):
メイン処理
if __name__ == "__main__":
main(sys.argv)
「 __name__ 」 には、スクリプトとして直接呼び出されたとき...
参考
-[[基本構文 - Python入門から応用までの学習サイト>http://w...
***MacでPython3 [#c8efcb87]
Yosemiteを使ってるとバージョンが2.7系で、、3.x系を使いた...
-[[pyenvとvirtualenvで環境構築 - Qiita>http://qiita.com/K...
-[[OSXでpyenvインストールメモ - Qiita>http://qiita.com/ry...
などを参考に、Python環境を管理するツールを入れます
$ brew install pyenv
$ echo 'export PYENV_ROOT=$HOME/.pyenv' >> ~/.bash_profile
$ echo 'export PATH=$PYENV_ROOT/bin:$PATH' >> ~/.bash_pr...
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
$ pyenv install 3.5.1
なんかエラーが出たら、たいがい
$ xcode-select --install
これもしくは、
$ sudo installer -pkg /Library/Developer/CommandLineTool...
(これはmojaveのばあい)
$ pyenv shell 3.5.1
$ python --version
Python 3.5.1
$
$ pyenv versions <-インストールされているモノの一覧。
* system (set by /Users/xxxx/.pyenv/version)
2.7.11
2.7.12
3.5.1
$
[[pyenvが必要かどうかフローチャート - Qiita>http://qiita....
***JSON文字列のDump [#s2abf34e]
r = requests.get('https://xxx/yyy.json')
result = json.dumps(r.json(),ensure_ascii=False, indent=...
print(result)
requests は pip(かpip3)などでインストールされてる前提で。。
[[[Python] JSONを扱う - YoheiM .NET>http://www.yoheim.net...
**関連リンク [#ke758226]
-[[[Python] 何度も調べてしまうリスト操作をまとめてみた - ...
-[[Python Tips:ライブラリをまとめてインストールしたい - ...
-[[Python の datetime オブジェクトと Unix 時間の相互変換...
-[[Python 3 で少しだけ便利になった datetime の新機能 - Qi...
----
この記事は
#vote(おもしろかった[2],そうでもない[0])
#comment
#topicpath
SIZE(10){現在のアクセス:&counter;}
ページ名: