【问题标题】:Data frame does not display column names数据框不显示列名
【发布时间】:2019-10-22 14:32:24
【问题描述】:

我编写了一个脚本,它首先运行 SQL 查询以从 Redshift(通过 Databricks)获取数据。然后,我想在熊猫数据框中显示它。问题是列的名称以某种方式被删除/不显示。为什么?

#SQL Query
query = """
SELECT * FROM table1 limit 1;  
"""

# Execute the query
try:
  cursor.execute(query)
except OperationalError as msg: 
  print ("Command skipped: ")

#Fetch all rows from the result
rows = cursor.fetchall()

# Convert into a Pandas Dataframe
df = pd.DataFrame( [[ij for ij in i] for i in rows] )

df.head()

输出:

如您所见,列名变成了数字(黄色)。目的是显示列名 1:Customer_id,列名 2:购买,列名 3:Product_id 等。

感谢您的帮助。谢谢!

【问题讨论】:

  • 使用pd.read_sql()
  • 您没有将列名传递给 pd.DataFrame,因此 pandas 分配了从 0 开始的默认列名
  • @Vaishali 哦,太好了,我该如何通过这些?
  • pd.DataFrame([[ij for ij in i] for i in rows] , columns = [...])
  • pd.read_sql() 神奇!谢谢

标签: python python-3.x pandas databricks


【解决方案1】:

根据@Chris 的建议,您可以通过以下方式使用pd.read_sql:-

query = """SELECT * FROM table1 limit 1;"""

connection = psycopg2.connect(user = 'your_username',
                                    password = 'password',
                                    host = 'host_ip',
                                    port = 5432,
                                    database = 'db_name')

data = pd.read_sql(sql=query, con=connection)

现在,当您打印 data 时,它也会显示列名!

【讨论】:

  • 我正在使用 mysql-connector 驱动程序中的 sql.connect() 而不是 psycopg2.connect()。
猜你喜欢
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2020-08-18
  • 2015-05-19
  • 2021-09-13
  • 2014-01-10
  • 2014-01-22
  • 2015-05-29
相关资源
最近更新 更多