Cucco’s Compute Hack

コンピュータ関係の記事を書いていきます。

リストの結合と、DBへの格納

長さが同じリストを、列が増える方向に連結して、DBに格納する検証コード。
Pandasを経由したほうが、SQLでのテーブル定義 をしなくてもよいから楽

プログラム

import pandas as pd
import sqlite3

# 長さが同じListを、列が増える方向に連結
# Index は無しで、DBに入れる。

# -------------------------------------------
# 結合
x = [1, 2, 3, 4, 5]
y = ['a', 'b', 'c', 'd', 'e']
z = [1.1, 2.2, 3.3, 4.4, 5.5]

# name はDBの列名になる。
s_x = pd.Series(data=x, name="x")
s_y = pd.Series(data=y)
s_y.name = "y"
s_z = pd.Series(data=z)

# axis=0 行を増やす方向に連結
axis = 0
df1 = pd.concat([s_x, s_y], axis=axis)
print(df1, type(df1))

# axis=1 列を増やす方向に連結
axis = 1
df1 = pd.concat([s_x, s_y], axis=axis)
print(df1, type(df1))

df2 = pd.concat([s_x, s_y], axis=axis)
print(df2, type(df2))

df3 = pd.concat([s_x, s_y, s_z], axis=axis)
print(df3, type(df3))

# -------------------------------------------
# DB書き込み

con = sqlite3.connect(":memory:")
con.isolation_level = None  # None で自動コミットモード
cur = con.cursor()
cur.execute('PRAGMA temp_store=MEMORY;')
cur.execute('PRAGMA journal_mode=MEMORY;')

# DBへの書き込み df3を書き込み。インデックスは無し。
table_name = 'test_table'
df3.to_sql(name=table_name, con=con, index=False)

# テーブル定義の確認
tmp = cur.execute("SELECT * FROM sqlite_master WHERE type='table'")
print("# テーブル定義の確認")
for row in tmp:
    print(row)

# 書き込んだの内容の確認
tmp = cur.execute("SELECT * FROM {0}".format(table_name))
print("# テーブルの内容の確認")
for row in tmp:
    print(row)

con.close()

実行結果

(base) C:\>python C:\hello_pandas\hello_concat.py
0    1
1    2
2    3
3    4
4    5
0    a
1    b
2    c
3    d
4    e
dtype: object <class 'pandas.core.series.Series'>
   x  y
0  1  a
1  2  b
2  3  c
3  4  d
4  5  e <class 'pandas.core.frame.DataFrame'>
   x  y
0  1  a
1  2  b
2  3  c
3  4  d
4  5  e <class 'pandas.core.frame.DataFrame'>
   x  y    0
0  1  a  1.1
1  2  b  2.2
2  3  c  3.3
3  4  d  4.4
4  5  e  5.5 <class 'pandas.core.frame.DataFrame'>
# テーブル定義の確認
('table', 'test_table', 'test_table', 2, 'CREATE TABLE "test_table" (\n"x" INTEGER,\n  "y" TEXT,\n  "0" REAL\n)')
# テーブルの内容の確認
(1, 'a', 1.1)
(2, 'b', 2.2)
(3, 'c', 3.3)
(4, 'd', 4.4)
(5, 'e', 5.5)