[英]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.