5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[python]jupyternotebookからpostgresqlサーバーへ接続してdataframeとして取り込む方法

Last updated at Posted at 2019-01-05

はじめに

jupyternotebookからpostgresサーバーへ接続して、データフレームとして読み込む方法を記載していきます

前提

以前こちらの記事を投稿したのですが、こちらのサーバーが起動されている状態であることを前提に進めていきます。

導入

まずはpythonからpostgresqlサーバーに接続するためのドライバーをインストールします。今回はpsycopg2を利用します。

$ pip3 install psycopg2-binary

dbの確認

今回接続するdbを確認します。

$ psql -l
                               List of databases
   Name    | Owner  | Encoding |   Collate   |    Ctype    | Access privileges 
-----------+--------+----------+-------------+-------------+-------------------
 postgres  |  hoge  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | 
 template0 |  hoge  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/hoge        +
           |        |          |             |             | hoge=CTc/hoge
 template1 |  hoge  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/hoge        +
           |        |          |             |             | hoge=CTc/hoge
(3 rows)

接続

言わずもがなの起動

$ jupyter notebook

もしくは

$ ipython notebook

起動されたら新しいpythonファイルを開いて接続を行います。

import psycopg2

connection = psycopg2.connectconnection = psycopg2.connect(host="localhost", database="postgres", user="hoge",password="password")

読み込み

今回はデータフレームとして読み込みを行います。

sql_query = "select * from access_log"#SQL文

import pandas as pd

df = pd.read_sql(sql_query, connection)
connection

結果

今回はこちらのサイトのサンプルデータを利用しています。

スクリーンショット 2019-01-05 18.49.54.png

終わり

とても簡単に接続ができました。

参考サイト

psycopg2でPyhtonからPostgreSQLに接続する
PostgreSQL/データベース一覧を調べる方法
PostgreSQLをPythonからpsycopg2を使っていじる
PythonからPostgreSQLに接続する方法

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?