LoginSignup
4
7

More than 5 years have passed since last update.

Windows10でPython3の開発環境と使い方まとめ

Last updated at Posted at 2017-03-16

概要

Windows10でPython3の環境を構築します。生のPythonを入れて必要に応じて様々なライブラリを随時追加していきます。CLIはcmd.exeではなくPowerShellを使います。

Pythonのインストール

pipの設定

何もしなくても入っている

> python -m pip --version
================================================
pip 9.0.1 from C:\Users\ftakao2007\AppData\Local\Programs\Python\Python36\lib\site-packages (python 3.6)
================================================

ansibleのインストール(保留中)

Ansible2.2のPython3.6.1対応はまだされていない可能性があるので。。

### こんなエラー
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(26): error C2061: syntax error: identifier 'intmax_t'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2061: syntax error: identifier 'rem'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(27): error C2059: syntax error: ';'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(28): error C2059: syntax error: '}'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2061: syntax error: identifier 'imaxdiv_t'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(30): error C2059: syntax error: ';'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(40): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2146: syntax error: missing ')' before identifier '_Number'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2061: syntax error: identifier '_Number'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(41): error C2059: syntax error: ';'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(42): error C2059: syntax error: ')'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(45): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2146: syntax error: missing ')' before identifier '_Numerator'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2061: syntax error: identifier '_Numerator'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ';'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(46): error C2059: syntax error: ','
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(48): error C2059: syntax error: ')'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(50): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(56): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(63): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(69): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(76): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(82): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(89): error C2143: syntax error: missing '{' before '__cdecl'
   C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h(95): error C2143: syntax error: missing '{' before '__cdecl'
   error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
### PowerShellの管理者権限でinttypes.hを開いて編集して保存
> notepad 'C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h'
================================================
typedef struct
{
#define intmax_t long long               ### これを追記
#define uintmax_t unsigned long long     ### これを追記
    intmax_t quot;
    intmax_t rem;
} _Lldiv_t;

typedef _Lldiv_t imaxdiv_t;
================================================

### pycryptoのインストール
> python -m pip install pycrypto
================================================
Collecting pycrypto
  Using cached pycrypto-2.6.1.tar.gz
Building wheels for collected packages: pycrypto
  Running setup.py bdist_wheel for pycrypto ... done
  Stored in directory: C:\Users\ftakao2007\AppData\Local\pip\Cache\wheels\80\1f\94\f76e9746864f198eb0e304aeec319159fa41b082f61281ffce
Successfully built pycrypto
Installing collected packages: pycrypto
Successfully installed pycrypto-2.6.1
================================================

### PowerShellの管理者権限でinttypes.hを開いてさっき追記した箇所を削除して保存
> notepad 'C:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt\inttypes.h'
================================================
typedef struct
{
    intmax_t quot;
    intmax_t rem;
} _Lldiv_t;

typedef _Lldiv_t imaxdiv_t;
================================================

### ansibleのインストール
> python -m pip install ansible
  • 事後作業
    • このままだとansibleに実行権限が無く、単にansibleのファイルを開いてしまう動作になる
    • (対応方法確認中...)

venvの設定

何もしなくても入っている

### 管理者権限でPowerShellを起動し、現在のポリシーを確認
> Get-ExecutionPolicy
================================================
Restricted
================================================

### ポリシーの変更(署名無しでもローカルのスクリプトは実行できるようにする)
> Set-ExecutionPolicy RemoteSigned
================================================
実行ポリシーの変更
実行ポリシーは、信頼されていないスクリプトからの保護に役立ちます。実行ポリシーを変更すると、about_Execution_Policies
のヘルプ トピック (http://go.microsoft.com/fwlink/?LinkID=135170)
で説明されているセキュリティ上の危険にさらされる可能性があります。実行ポリシーを変更しますか?
[Y] はい(Y)  [A] すべて続行(A)  [N] いいえ(N)  [L] すべて無視(L)  [S] 中断(S)  [?] ヘルプ (既定値は "N"): Y
================================================

> Get-ExecutionPolicy
================================================
RemoteSigned
================================================

venv実行テスト

### ワークスペースの作成
> python -m venv venvtest

### ワークスペースに移動
> cd venvtest

### アクティベート
> .\Scripts\Activate.ps1
================================================
### 以下のように先頭に(venvtest)がつく
(venvtest) PS C:\Users\ftakao2007\PycharmProjects\python\venv\venvtest>
================================================

### PowerShellではなくcmd.exeの場合は以下
### > Scripts\activate.bat
###

### ディアクティベート
> deactivate

PythonでMySQLに接続するための設定

Ununtu16.04の場合

# apt-get install libmysqlclient-dev
# pip install mysqlclient

これで import MySQLdb ができるようになる

PythonでMongoDBに接続するための設定

Ununtu16.04の場合

# apt-get install pymongo

これで import pymongo ができるようになる

import pymongo
import pandas as pd
from pymongo import MongoClient
client = MongoClient(host=['192.168.33.11:27017'])
db = client.joruri_plus
collection = db.plus_projects
data = pd.DataFrame(list(collection.find()))
data

Python周りのライブラリのインストール

  • IPython
    • Pythonの対話型インタプリタを強力に拡張したもの
      • 拡張された対話型シェル
      • 分離型プロセス間通信モデル
      • 並列コンピューティング機構
  • Jupyter
    • IPythonをサーバーで立ち上げてブラウザ上で実行できるようにしたもの
    • 元々がIPython Notebookという名前だった
### jupyterのインストール (ipythonも入る)
> python -m pip install jupyter

### jupyterの起動
> jupyter notebook

ruby連携

数値計算・機械学習ライブラリのインストール

  • NumPy
    • 数値計算を効率的に処理するためのライブラリ
  • SciPy
    • 様々な科学計算が実装されたライブラリ
    • 内部でNumPyが使われている
  • matplotlib
    • グラフ描画ライブラリ
    • 内部でNumPyが使われている
  • pandas
    • Pythonでデータ構造を触ったりデータ分析したりするときに便利なライブラリ
  • TendorFlow
    • Googleによって開発されている
    • ディープラーニングを実装するための機械学習ライブラリ
  • scikit-learn
    • Googleによって開発されている
    • 機械学習全般のアルゴリズムやデータ処理用関数をカバーしたライブラリ
      • SVM
      • 決定木
      • K-NN
      • K-means
      • 交差検定
      • 回帰分析
      • 主成分析
> python -m pip install numpy pandas matplotlib

PyCharmのインストール

Jupyter Notebook使い方

ウェブDBプレスvol97の伊藤直也さんの記事参考

Hello World

def hello():
    return "Hello World"

hello()   ### ここでCtrl+Enter
================================================
'Hello World'
================================================

図を表示する

  • 「%」では始まる命令はマジックコマンド
    • Jupyterへの命令
%matplotlib inline
import pandas as pd

df = pd.DataFrame([1,2,4,8,16,32,64,128,256])
df.plot()

スクリーンショット 2017-03-26 21.11.23.png

df.describe()

スクリーンショット 2017-03-26 21.12.25.png

Markdownと数式のテスト

# Markdownテスト

## リストテスト

* リスト1
* リスト2

## 数式のテスト

$ \sqrt{x^2 + y^2} $

スクリーンショット 2017-03-26 21.22.20.png

pandasの基本

  • データ構造
    • Series(シリーズ)
      • 一次元のデータ構造
    • DataFrame(データフレーム)
      • 二次元のデータ構造
    • 階層インデックス
      • より高次元のデータを扱うとき

データフレームの初期化

df = pd.DataFrame([1,2,3], columns=['value'])
df

image

タプル(イミュータブルなシーケンス型)のリストを渡す

pd.DataFrame([('apple',160),('orange',30),('kiwi',80)], columns=['name', 'price'])

image

ディクショナリ(連想配列、ハッシュみたいなもの)でリストを渡す

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

pd.DataFrame(data)

image

列の追加

値段と注文数を書けた合計金額を出す

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df['total'] = df['order'] * df['price']
df

image

インデックスの指定

data = {
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data, index=['apple', 'orange', 'kiwi'])
df

image

特定の行をシリーズとして取り出し

data = {
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data, index=['apple', 'orange', 'kiwi'])
df.ix['kiwi']

image

サイズの調査

data = {
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data, index=['apple', 'orange', 'kiwi'])
df.shape
================================================
(3, 2)
### 3行2列。indexは入らない
================================================

行や列の選択

fruitの列を選択

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df['fruit']

image

fruit, orderの2列選択

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df[['fruit','order']]

image

head, tail

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.head(2)

image

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.tail(2)

image

表示範囲をindexで指定

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df[0:2]

image

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df[1:]

image

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.loc[[0,2]]

image

サンプリング

実行する毎に抽出される行が変わる

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.sample(n=2)

image

条件を指定した絞込

SQLのwhere句みたいなもの

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df[df.price > 50]

image

Where句を使うと条件にマッチしないものはNaN(Not a number:非数)で埋まる。
pandasでは欠損値として扱われる

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.where(df.price > 50)

image

欠損値は削除したり埋めたりできる

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.where(df.price > 50).dropna()

image

data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.where(df.price > 50).fillna(df.mean())

image

任意の関数の適用

  • axis=0 : 行方向
  • axis=1 : 列方向
  • upper : 大文字にする
data = {
    'fruit' : ['apple', 'orange', 'kiwi'],
    'price' : [160,30,80],
    'order' : [12,30,8]
}

df = pd.DataFrame(data)
df.apply(lambda x: x.fruit.upper(), axis=1)

fruitの列を大文字にする

image

CSVのソート

CSV読み込み

df = pd.read_csv('./ruby_1.csv')
df

image

Rubyの点数が高い順

sort_by_ruby = df.sort_values(by='ruby', ascending=False)
sort_by_ruby[['name', 'ruby']]

image

平均を追加

df['mean'] = df.mean(axis=1)
df

image

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7