如何将python中的输出视为类似SQL表格式的输出
我写的代码和输出附在下面。。 在上面的图片中找到它如何将python中的输出视为类似SQL表格式的输出,python,sql,postgresql,format,Python,Sql,Postgresql,Format,我写的代码和输出附在下面。。 在上面的图片中找到它 import psycopg2 conn = psycopg2.connect("dbname='news' user='postgres'") cursor = conn.cursor() cursor.execute( "SELECT * FROM authors") results = cursor.fetchall() print (results) conn.cl
import psycopg2
conn = psycopg2.connect("dbname='news' user='postgres'")
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM authors")
results = cursor.fetchall()
print (results)
conn.close
代码和输出:
我想要的输出格式:
您可以使用库
pandas
为此,它有方便的方法显示数据,并为您进行列对齐
以下是一个小样本:
import pandas as pd
print(pd.DataFrame([(1,2,3), (1,2,3)], columns=['a', 'b', 'c']))
导致输出
a b c
0 1 2 3
1 1 2 3
在您的情况下,您需要使用:
df = pd.DataFrame(results, columns=['name', 'description', 'id'])
我只是猜了一下列名…我在这里看第二个答案。没有提到熊猫,为什么要提出来?因为它能完成任务。你也可以用100种其他方式完成任务,为什么不全部列出呢?:)