【发布时间】:2015-07-17 10:12:58
【问题描述】:
我正在尝试使用 psycog2 对查询结果执行操作。因此,我必须将结果转换为 pandas DataFrame。但是当我使用下面的代码并打印时,只打印列名而不打印行。我也使用了“pd.DataFrame.from_records”,但没有用。
import psycopg2
import pandas as pd
import numpy as np
conn_string = "Connect_Info"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute(query)
rows=pd.DataFrame(cursor.fetchall(),columns=['page_num','Frequency'])
for row in rows:
print row
conn.commit();
conn.close();
cursor.fetchall() 的结果 -
(1L, 90990L)
(3L, 6532L)
(2L, 5614L)
(4L, 4016L)
(5L, 2098L)
(6L, 1651L)
(7L, 1158L)
(8L, 854L)
(9L, 658L)
(10L, 494L)
(11L, 345L)
(12L, 301L)
(13L, 221L)
(15L, 152L)
(14L, 138L)
(16L, 113L)
(17L, 93L)
(18L, 73L)
(20L, 62L)
(19L, 55L)
(22L, 44L)
(21L, 35L)
(23L, 29L)
(25L, 24L)
(27L, 19L)
(26L, 18L)
【问题讨论】:
-
你能把 cursor.fetchall() 的结果放在这里吗?
-
你能打印 cursor.fetchall() 的输出吗?也不确定您是否可以通过这种方式遍历 DataFrame
-
从 df 返回的迭代是列而不是行
-
注1:为了获取数据,你最好使用
read_sql_query,然后上面的一切就几乎变成了一条线(见我的回答)。 -
注2:你能澄清一下你想做什么样的操作吗?在 DataFrame 的行上手动迭代不是很有效,并且在大多数情况下是不需要的(大多数操作可以使用矢量化方法完成)。
标签: python pandas dataframe psycopg2