将查询结果转换为Python中的DataFrame [英] Converting query results into DataFrame in python

查看:1174
本文介绍了将查询结果转换为Python中的DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用psycog2对查询结果执行操作。因此,我必须将结果隐藏到大熊猫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'])

行中的行:
打印行

conn.commit();
conn.close();

cursor.fetchall()的结果 -



$ 1
(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)


解决方案

这是当您遍历数据框时会发生什么,您会看到列名。如果你想看df只打印df。要查看行:

  for ind,row in df.iterrows():
print(row.values)

或.values:

  for df.values中的行:
print(row)


I am trying to perform manipulation on the result from a query using psycog2. Thus I have to covert result into pandas DataFrame. But when i use the following code and print, only the columns name are printed not the rows. I used 'pd.DataFrame.from_records' too but that did not work.

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();

The result of 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)

解决方案

That is exactly what should happen when you iterate over a dataframe, you see the column names. If you want to see the df just print the df. To see the rows:

for ind, row in df.iterrows(): 
    print(row.values)

Or .values:

for row in df.values:
   print(row)

这篇关于将查询结果转换为Python中的DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆