【问题标题】:Select columns based on values of another column if present in a list如果存在于列表中,则根据另一列的值选择列
【发布时间】:2019-04-03 18:46:29
【问题描述】:

我正在尝试使用 pandas.read_gbq 根据列表中存在的列 C 的值从我的 Bigquery 表中选择列 A 和 B。但是,当我使用format 在查询字符串中插入列表时,列表的内容会被[] 方括号括起来。这打破了我的查询。

我在查询字符串上使用了replace 来手动删除方括号。

values_in_list = ['a', 'b', 'c']
query = """
SELECT
  column_A,
  column_B

FROM
  my_table

WHERE
 column_C IN ({})
""".format(values_in_list).replace('[', '').replace(']', '')
query_df = pandas.read_gbq(query, project_id='some-project', dialect='standard')

这样就完成了工作。我想知道是否有比暴力破解更优雅的解决方案。

【问题讨论】:

  • 最好通过查询参数传递values_in_list,看这个example
  • 非常感谢您的回复。我按照您提供的链接进行操作。当我使用 'type': 'STRING' paramterType 时,此查询仅返回列表的第一个元素之类的值。当我尝试'type': 'ARRAY' 时,它返回了一个基于GenericGBQExceptionBadRequest

标签: python pandas google-bigquery


【解决方案1】:

我不确定pandas.read_gbq 是否支持query_config 关键字arg 中的ArrayQueryParameters。这是我的解决方法:

from google.cloud import bigquery
client = bigquery.Client()

values_in_list = ['a', 'b', 'c']
query = """
SELECT
  column_A,
  column_B

FROM
  my_table

WHERE
 column_C IN UNNEST(@col_c_vals)
"""

query_params = [bigquery.ArrayQueryParameter('col_c_vals', 'STRING', values_in_list)]
job_config = bigquery.QueryJobConfig()
job_config.query_parameters = query_params
query_df = client.query(query, job_config=job_config).to_dataframe()

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多