python - sqlite 如何在 Pandas 数据框中返回“PRAGMA table_info()”的输出?
问题描述
"PRAGMA table_info()"
在 Python 中使用 sqlite3 模块,有没有办法在 Pandas 数据框中返回输出?我不确定如何在任何 Pandas read_sql 函数中实现它。
例如,
conn = sqlite3.connect(db)
info = conn.execute("PRAGMA table_info('mytable')").fetchall()
conn.close()
print info
返回[(0, u'id', u'INTEGER', 0, None, 1), (1, u'name', u'TEXT', 1, None, 0), (2, u'date', None, 0, current da...
使用 SQLite 命令行,PRAGMA table_info(mytable);
返回以下内容,这更容易阅读:
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 0 1
1 name text 1 0
2 date 0 current_da 0
解决方案
如果你有
info = [(0, u'id', u'INTEGER', 0, None, 1), (1, u'name', u'TEXT', 1, None, 0), (2, u'date', None, 0, 'current da', 0)]
然后
import pandas as pd
df = pd.DataFrame(info, columns=['cid', 'name', 'type', 'notnull', 'dflt_value', 'pk'])
print(df)
结果:
cid name type notnull dflt_value pk
0 0 id INTEGER 0 None 1
1 1 name TEXT 1 None 0
2 2 date None 0 current da 0
编辑:
未测试
import sqlite3
import pandas as pd
conn = sqlite3.connect(db)
cur = conn.cursor()
info = cur.execute("PRAGMA table_info('mytable')").fetchall()
columns = [item[0] for item in cur.description]
df = pd.DataFrame(info, columns=columns)
print(df)
没有cursor
and也一样fetchall()
import sqlite3
import pandas as pd
conn = sqlite3.connect(db)
info = conn.execute("PRAGMA table_info('mytable')")
columns = [item[0] for item in info.description]
df = pd.DataFrame(info, columns=columns)
print(df)
它也应该适用于pd.read_sql()
和pd.read_sql_query()
import sqlite3
import pandas as pd
conn = sqlite3.connect(db)
df = pd.read_sql("PRAGMA table_info('mytable')", conn)
#df = pd.read_sql_query("PRAGMA table_info('mytable')", conn)
print(df)