[英]What's the Python/pandas equivalent to this SQL for finding both the max value and column-name?
[英]How to get table column-name/header for SQL query in python
我在 Pandas 数据框中有数据,我使用 Python 将其存储在 SQLITE 数据库中。 当我尝试查询其中的表时,我能够获得结果但没有列名。 有人可以指导我。
sql_query = """Select date(report_date), insertion_order_id, sum(impressions), sum(clicks), (sum(clicks)+0.0)/sum(impressions)*100 as CTR
from RawDailySummaries
Group By report_date, insertion_order_id
Having report_date like '2014-08-12%' """
cursor.execute(sql_query)
query1 = cursor.fetchall()
for i in query1:
print i
下面是我得到的输出
(u'2014-08-12', 10187, 2024, 8, 0.3952569169960474)
(u'2014-08-12', 12419, 15054, 176, 1.1691244851866613)
我需要做什么才能以带有列名的表格形式显示结果
在符合 DB-API 2.0 的客户端中, cursor.description
是以下形式的 7 项序列的序列(<name>, <type_code>, <display_size>, <internal_size>, <precision>, <scale>, <null_ok>)
,每列一个,如所描述这里。 注意如果执行语句的结果为空,则description
将为None
。
如果你想创建一个列名列表,你可以像这样使用列表理解: column_names = [i[0] for i in cursor.description]
然后对它们做任何你想做的事情。
或者,您可以将连接对象的row_factory
参数设置为提供列名和结果的参数。 在这里可以找到 SQLite 基于字典的行工厂的示例,您可以在下面看到对sqlite3.Row
类型的讨论。
尝试 Pandas .read_sql(),我现在无法检查它,但它应该是这样的:
pd.read_sql( Q , connection)
我的英语很差,我写了一个示例,看看它,使用 cx_Oracle,但 mysql 也一样。
import cx_Oracle
def test_oracle():
connection = cx_Oracle.connect('user', 'password', 'tns')
try:
cursor = connection.cursor()
cursor.execute('SELECT day_no,area_code ,start_date from dic.b_td_m_area where rownum<10')
#only print head
title = [i[0] for i in cursor.description]
print(title)
# column info
for x in cursor.description:
print(x)
finally:
cursor.close()
if __name__ == "__main__":
test_oracle();
第 1 步:选择您的引擎,如 pyodbc、SQLAlchemy 等。
第二步:建立连接cursor = connection.cursor()
第三步:执行SQL语句cursor.execute("Select * from db.table where condition=1")
第 4 步:从连接变量描述中提取 Header
headers = [i[0] for i in cursor.description]
print(headers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.