• Skip to main content
  • Skip to primary sidebar

学習記録

ATOMでコンソール

2018年9月3日 by 河副 太智 Leave a Comment

ATOM画面左下の+を押して、”ipython”と入力する

Filed Under: Python 基本 Tagged With: ATOM, ipython, コンソール

np.array はN次元配列を扱うためのクラス

2018年9月1日 by 河副 太智 Leave a Comment

数学の概念で言えば,1次元の場合はベクトルに,
2次元の場合は行列に,そして3次元以上の場合はテンソルに該当

1
2
3
4
5
6
7
8
9
10
11
12
In [1]: import numpy as np
 
In [2]: mylist=[1,2,3,4]
 
In [3]: np.array(mylist)
Out[3]: array([1, 2, 3, 4])
 
In [4]: mylist
Out[4]: [1, 2, 3, 4]
 
In [5]: type(mylist)
Out[5]: list

np.arrayでarrayに変換しても一時的にしか変換できていません

継続してarray型にするには変数に入れる必要があります。

1
2
3
4
5
6
7
In [6]: arr = np.array(mylist)
 
In [7]: type(arr)
Out[7]: numpy.ndarray
 
In [8]: arr
Out[8]: array([1, 2, 3, 4])

このようにすれば変数arrはいつまでもarray型をキープできます。

 

 

2次元配列とは以下のようなもので[[ と ]]のダブルカッコがあります

1
2
3
4
5
6
In [12]: np.zeros((2,20))
Out[12]:
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0.]])

np.zeros()の第一引数は列の数で第二引数は行の数となり
全て0で満たされます。

 

 

2次元配列から一を指定して値を取得する方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
In [20]: mat
Out[20]:
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
 
In [21]: mat[5,2]
Out[21]: 52

 

カラム、列の値を縦一直線に欲しい場合は”:”を使う

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 
       [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
       [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
       [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
       [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
 
 
In [23]: mat[:,2]
Out[23]: array([ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92])

 

行の値を横一直線に欲しい場合は以下のようにする

1
2
In [24]: mat[2,:]
Out[24]: array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29])

 

条件に合う値のみを抽出

1
2
3
4
5
In [25]: mat[mat>50]
Out[25]:
array([51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

 

Filed Under: Numpy

前の値を参照しつつ次の値を追加

2018年9月1日 by 河副 太智 Leave a Comment

以下のように過去のlistに対し、新たな値を追加していきます。

自作関数add_value()を3回実行すればlistの過去の値に対し
新たなデータが次々と追加されていきます。
まさにブロックチェーンの基礎ですね

1
2
3
4
5
6
7
8
9
blockchain=[[1]]
 
def add_value():
    blockchain.append([blockchain[-1],6])
    print(blockchain)
 
add_value()
add_value()
add_value()

>>>[[1], [[1], 6]]
>>>[[1], [[1], 6], [[[1], 6], 6]]
>>>[[1], [[1], 6], [[[1], 6], 6], [[[[1], 6], 6], 6]]

Filed Under: ブロックチェーン

Blockchainプログラミング基礎:自作関数でリスト作成

2018年9月1日 by 河副 太智 Leave a Comment

自作関数を使って変数blockchainに値を追加
まず最初にblockchain=[1]としてリストの値を1のみにして
そこに色々足してみます。

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(0)
    print(blockchain)
 
add_value()

>>[1, 0]
リストに0が追加されました。

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(blockchain[0])
    print(blockchain)
 
add_value()

>[1, 1]
blockchain[0]の値と同じものを追加するという意味なので
1が追加される

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append([blockchain[0],5.3])
    print(blockchain)
 
add_value()

>[1, [1, 5.3]]
ちょっとややこしいけど[]で囲まれている場合は
blockchain[0]の値と同じものと5.3を別の[]に入れて、
元の値1のカンマで区切った次の位置に追加している。

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(blockchain[-1])
    print(blockchain)
 
add_value()

[1, 1]
blockchain[-1]と指定するとlistの値の一番最後の値を意味する
ブロックチェーンでは最後の値にどんどん新たな情報を追加していくので
この[-1]の概念は非常に重要です。

Filed Under: ブロックチェーン

国連apiによるhs統計

2018年8月23日 by 河副 太智 Leave a Comment

パラメーター

中国からアメリカ向け輸出
※2019/3/7の時点で国連から該当2018年度データはまだ入手できていないと返信

1
https://comtrade.un.org/api/get?type=C&freq=A&px=HS&ps=2018&r=156&rg=2

 

中国から全国向け輸出

1
https://comtrade.un.org/api/get?type=C&freq=M&px=HS&ps=201012&r=156&rg=2&cc=382490&fmt=csv

 

1
2
http://comtrade.un.org/api/get?
max=50000&type=C&freq=A&px=HS&ps=2013&r=156&p=0&rg=all&cc=382490&fmt=csv

pxがhsの年度
ccがhsコード
psが年月
rがレポート国(国コード検索:中国は156 イギリスは826アメリカは842)

 

各国データの個別詳細(FOB,CIF等)はExplanatory Notesを参照

 

 

■コード全体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import pandas as pd
import plotly.offline as pyo
import plotly.graph_objs as go
import urllib.request
 
 
 
#パラメーターの作成
#trade data type C Commodities S Services
datatype = "type=C"
#china=156,UK=826,US=842,jp=392or all
reporting_area = "&r=156"
#Annual=A,Monthly=M
frequency = "&freq=A"
#YYYY or YYYYMM or now or recent
time_period = "&ps=recent"
# Harmonized System (HS)
classification = "&px=H4"
#china=156,UK=826,US=842,or all
partner_area = "&p=all"
# 1 (imports) and 2 (exports),
import_or_export = "&rg=2"
#HS CODE
classification_code = "&cc=630532"
#csv or json
fmt = "&fmt=csv"
url = ("https://comtrade.un.org/api/get?"+datatype + reporting_area+frequency+time_period+classification+partner_area+
      import_or_export+classification_code+fmt)
 
 
#csvをdfに入れる
 
res = urllib.request.urlopen(url)
df = pd.read_csv(res)
 
#最新年を取得
newest = (df["Year"].max())
 
#最新年のデータのみを取得
df_n = df[df["Year"] == newest]
 
#valueが高い順に並べ替え
df_s = df_n.sort_values('Trade Value (US$)', ascending=False)
 
#上位10件を取得してリスト化
partner = []
for var in range(1, 5):
    partner.append(df_s.iat[var, 12])
 
 
data = []
for i in partner:
    df2 = df[df["Partner"] == i]
    trace = go.Scatter(x=df2["Year"],
                       y=df2["Trade Value (US$)"],
                       mode="lines",
                       name = i)
    data.append(trace)
 
pyo.plot(data)

■必要なカラム一覧
[ Year]
[ Trade Flow]
[ Reporter]
[ Partner]
[ Commodity Code]
[ Commodity]
[ Qty Unit]
[ Alt Qty Unit]
[Netweight (kg)]
[Trade Value (US$)]

Filed Under: プログラミング

さくらvpsにflaskを入れてwebapp作成

2018年8月10日 by 河副 太智 Leave a Comment

rootログイン

FTPでのファイル転送はrootで行う為に以下のサイトを参考

Ubuntu 16.04: rootでログインする

ソフトウェアのインストール

– Go to the server root directory with “cd /”
– yumでInstall required software with
“yum install python-virtualenv nginx gunicorn supervisor python-pip”

– apt-getでInstall required software with “
apt-get install python-virtualenv nginx gunicorn supervisor python-pip

 

ディレクトリの作成

– Create a new directory for the virtual environment with
“mkdir /opt/envs”

– Create a virtual environment with virtualenv
“virtualenv /opt/envs/virtual”

– Activate the virtual environment
“. /opt/envs/virtual/bin/activate”

– Install Python dependencies
“pip install bokeh”
“pip install flask”
“pip install gunicorn”

– Create a new directory inside the nginx server
“mkdir /var/log/nginx/flask”

– Create a new directory for uploading app files
“mkdir /opt/webapps” “mkdir /opt/webapps/bokehflask”

 

configuration filesの作成

– Make sure you have your configuration files ready
which are bokeh_serve.conf, flask.conf and default.

 

FTPアップロード

– Locate your local project directory on the left panel and select your
Python files and the templates directory or any other associated local directory,
but not configuration files

– Locate and select the server directory on the right panel and click Upload
/opt/webapps/bokehflaskにapp.pyとrandom_generator.pyをアップする

 

– Upload the file named “default” to
/etc/nginx/sites-available
using the same procedure

– Upload files
“bokeh_serve.conf”
and
“flask.conf”
to /etc/supervisor/conf.d using the same procedure

サーバー上での調整

–  app.py を編集

以下のコマンドで開く
“nano /opt/webapps/bokehflask/app.py”

– インポート文を追加
“from werkzeug.contrib.fixers import ProxyFix”
to the remote app.py file.

– Modify the index function as follows:

1
2
3
4
5
def index():
    url="http://104.236.40.212:5006"
    session=pull_session(url=url,app_path="/random_generator")
    bokeh_script=autoload_server(None,app_path="/random_generator",session_id=session.id, url=url)
    return render_template("index.html", bokeh_script=bokeh_script)

– Add “app.wsgi_app = ProxyFix(app.wsgi_app)” to the remote app.py file after the index function.
– Save the file by pressing Control-X, then type y and then hit Enter.

–  bokeh_serve.confを編集

以下のコマンドで開く
“nano /etc/supervisor/conf.d/bokeh_serve.conf”
and put your IP for –allow-websocket-origin and your IP and port 5006 for –host

 

実行

– Start the nginx webserver with
“service nginx restart”

– Start supervisor with
“service supervisor restart”

– Start flask with
“supervisorctl restart flask”

– Start bokeh server with
“supervisorctl restart bokeh_serve”

– Visit your app in the browswer at http://160.16.225.109 (put your own IP)

Filed Under: Bokeh, flask

  • « Go to Previous Page
  • Page 1
  • Interim pages omitted …
  • Page 15
  • Page 16
  • Page 17
  • Page 18
  • Page 19
  • Interim pages omitted …
  • Page 66
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in