2
6

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 5 years have passed since last update.

49日目。pandas経由でCSVをsqlliteにぶっこんだら便利でした。

Last updated at Posted at 2019-07-28

前回の続きです。

48日目。pandasで10万×1万のCSVをマージしたら簡単・早くて驚きました!

for..loopだと終わらないので、pandasのDFに入れてマージしたら一瞬で片付いてやった!と思ったのですが、データを綺麗に揃えるのが大変でうんざりでした。何万行もあるのに一行ダメだとそこで止まる。止まっては直し、また止まっては直し・・・

そこで、pythonの標準機能で使えるデータベース、sqlliteを試してみました。

まずCSVをテーブルにどんどん入れていきます。

importcsv.py
import sqlite3
import pandas as pd

# pandasでカレントディレクトリにあるcsvファイルを読み込む
df = pd.read_csv("test999.csv")

# カラム名はAから順番に。Excelで開いたときに探しやすくて便利なので。
df.columns=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

dbname = 'TEST.db'
conn = sqlite3.connect(dbname)
cur = conn.cursor()

# table名はsample、tableがあったらappendする。
df.to_sql('sample', conn, if_exists='append')

cur.close()
conn.close()

シンプルですね。

データをどかどか入れたら読み出します。

selectdb.py

import sqlite3

dbname = 'TEST.db'
conn = sqlite3.connect(dbname)
cur = conn.cursor()

def getname(sampleid):
	cur.execute('SELECT * FROM sample where A=' + str(sampleid))
	return cur.fetchall()

# IDが一致した列をもってくる。
df = getname(1234567890)
print(df)

# データは「タプル」にはいっている。
# 目的のデータのみ表示する例。
df1 = df[2][4]
print(df1)

# 最後にカーソルを閉じる。
cur.close()
conn.close()

はやっ!

一瞬でした。

元のデータが穴ぼこだらけでも良いのが助かります。
SQLでマージしてもいいし、DFにもってきてマージしてもいいし。
何かと便利になりそうです。

2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?