【问题标题】:Select specific columns to read from PostgreSQL based on python list根据 python 列表选择要从 PostgreSQL 中读取的特定列
【发布时间】:2018-05-25 22:52:24
【问题描述】:

我有两个列表:一个包含分类变量的列名,另一个包含如下所示的数字。

cat_cols = ['stat','zip','turned_off','turned_on']
num_cols = ['acu_m1','acu_cnt_m1','acu_cnt_m2','acu_wifi_m2']

这些是 Redshift 表中的列名。

我想将这些作为参数传递以仅从 Redshift(PostgreSql) 中的表中提取数字列,将其写入 csv 并关闭 csv

接下来我只想拉出cat_cols 并打开csv 然后附加到它并关闭它。

到目前为止我的查询:

#1.Pull num data:
seg = ['seg1','seg2']
sql_data = str(""" SELECT {num_cols} """ + """FROM public.""" + str(seg) + """ order by random() limit 50000 ;""")
df_data = pd.read_sql(sql_data, cnxn)

# Write to csv.
df_data.to_csv("df_sample.csv",index = False)

#2.Pull cat data:
sql_data = str(""" SELECT {cat_cols} """ + """FROM public.""" + str(seg) + """ order by random() limit 50000 ;""")
df_data = pd.read_sql(sql_data, cnxn)
# Append to df_seg.csv and close the connection to csv.
with open("df_sample.csv",'rw'):
    ## Append to the csv ##

这是我第一次尝试基于 python 列表进行选择性查询,因此停留在如何将列表作为列名传递以从表中进行选择。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python postgresql pandas


    【解决方案1】:

    如果您想以字符串表示形式进行查询,您最好使用format 方法或f-strings(需要python 3.6+)。

    针对您的情况的示例,仅具有内置 format 函数。

    seg = ['seg1', 'seg2']
    num_cols = ['acu_m1','acu_cnt_m1','acu_cnt_m2','acu_wifi_m2']
    
    query = """
    SELECT {} FROM public.{} order by random() limit 50000;
    """.format(', '.join(num_cols), seg)
    print(query)
    

    如果您只想使用seg 数组中的一项,请在format 函数中使用seg[0]seg[1]

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多