【问题标题】:Redshift python connector columns names are byte stringRedshift python连接器列名称是字节字符串
【发布时间】:2021-10-28 18:38:44
【问题描述】:

假设我在 redshift 中有下表:

a | b
-----
1 | 2
3 | 4

如果我想将它从 Redshift 中提取到 pd.DataFrame,我可以执行以下操作:

import redshift_connector
import pandas as pd

query = 'SELECT * FROM table'
conn = redshift_connector(user=user, host=host, password=password, port=port, database=database)

df = pd.read_sql_query(query, conn)

我正在使用以下包redshift_connector。但问题是df 中的列名是字节串:

df['a']

这将返回错误,因为列的名称是 b'a'。有谁知道任何解决方法?我已经使用psycopg2 编写了使用普通字符串的代码,因此希望有一个不会对代码进行太多更改的解决方案。

编辑:

版本

Python = 3.9.7

红移连接器 = 2.0.889

熊猫 = 1.2.5

【问题讨论】:

    标签: python pandas amazon-redshift


    【解决方案1】:

    你可以用一行来解决这个问题

    df.columns = [col.decode("utf-8") for col in df.columns]
    

    或者不要使用pd.read_sql_query,而是使用文档中建议的连接方法

    cursor: redshift_connector.Cursor = conn.cursor()
    cursor.execute("SELECT * FROM table")
    
    result: pd.DataFrame = cursor.fetch_dataframe()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2014-03-23
      • 2019-05-20
      相关资源
      最近更新 更多