【问题标题】:Using JayDeBe and Amazon Redshift, is there a way to automatically pull the associated column names from within the query?使用 JayDeBe 和 Amazon Redshift,有没有办法从查询中自动提取关联的列名?
【发布时间】:2020-01-02 13:12:46
【问题描述】:

JayDeBe 已全部设置完毕,查询 Redshift 工作正常,但我需要找到一种方法来返回列名,这在将列表转换为 Pandas 数据框时会有所帮助

这是我用来执行查询的代码:

curs = conn.cursor()
curs.execute("select u.customer_name, u.status, from table.users u limit 10")
result = curs.fetchall()

根据查询的不同,列名会有所不同,因此在这种情况下设置格式将不起作用

我用谷歌搜索并尝试了各种建议,但都没有完成任务。

任何关于如何返回列名的帮助将不胜感激,非常感谢!

【问题讨论】:

    标签: amazon-redshift columnname jaydebeapi


    【解决方案1】:

    您可以使用类似这样的方式获取列名

    select ordinal_position as position,
           column_name,
           data_type,
           case when character_maximum_length is not null
                then character_maximum_length
                else numeric_precision end as max_length,
           is_nullable,
           column_default as default_value
    from information_schema.columns
    where table_name = 'table_name'
          and table_schema = 'Schema name'
    order by ordinal_position;
    

    你也可以试试 https://docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html

    【讨论】:

      【解决方案2】:

      感谢 Jon Scott 的回复,但我在这里创建了我正在寻找的答案,也许它可以帮助某人......

      curs = conn.cursor()
      curs.execute("select u.customer_name, u.status, from table.users u limit 10")
      # This next line was the key:
      colnames = [desc[0] for desc in curs.description]
      result = curs.fetchall()
      
      
      # Then converting to Pandas DataFrame and adding the column names
      df = pd.DataFrame(result)
      df.columns = colnames
      

      谢谢!

      【讨论】:

      • 哦,我明白了 :) 你只是想要返回对象中的 pandas 列名
      猜你喜欢
      • 2010-09-08
      • 2013-03-04
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2018-06-22
      • 2015-01-26
      相关资源
      最近更新 更多