【问题标题】:Looping through dataframe values in columns and using them as a FROM clause using SQL循环遍历列中的数据框值并使用 SQL 将它们用作 FROM 子句
【发布时间】:2021-09-30 14:32:58
【问题描述】:

我正在 Jupyter 笔记本中运行 BigQuery。

query ="""
SELECT 
    table_catalog, 
    table_schema, 
    table_name, 
FROM `Project-A.schema_A`.INFORMATION_SCHEMA.COLUMN_FIELD_PATHS
"""

输出将我带到下表:

# This is the output of the query
data = {'table_catalog':['project-A', 'project-A', 'project-A', 'project-A','Project-A','Project-A','Project-A'],
        'table_catalog':['schema_A', 'schema_A', 'schema_A', 'schema_A','schema_A','schema_A','schema_A']
        'table_name':['Table_A', 'Table_B', 'Table_B', 'Table_C','Table_C','Table_A','Table_A']}
 
d# Create DataFrame
df = pd.DataFrame(data)
 

我想在FROM CLAUSE 中的下一个查询中使用 Table_A、Table_B 和 Table_C,使其看起来像:

query =f"""
SELECT
*
FROM Project-A.Schema_A.{I want to edit this dyanmically - either Table_A, Table_B, Table_C}"""

我尝试了以下方法,但都失败了,请帮助我:

list_of_tables = list(df['table_name'].unique())

def loop_tables(x):
    for tables in list_of_tables:
        if x == tables
# x = df['table_name']
loop_tables()

【问题讨论】:

    标签: python pandas for-loop google-bigquery jupyter-notebook


    【解决方案1】:

    试试这个

    def loop_tables():
        list_of_dataframes = []
        for table in list_of_tables:
            print(table)
            dynamic_sql = "select * from project.dataset."
            dynamic_sql += table
            df = client.query(dynamic_sql).to_dataframe()
            list_of_dataframes.append(df)
        return list_of_dataframes
            
    

    【讨论】:

    • 谢谢!跟进问题。现在,我可以使用list_of_dataframes[0] 访问数据帧,直到list_of_dataframes[13]。这些基于之前创建的list_of_tables 变量 --> ['table1', table2',table3',table4'....]。有没有一种快速的方法来获取 list_of_dataframes[0] == 'table1' 直到 list_of_dataframes[13] == 'table14'。谢谢!仍然掌握python快捷方式的窍门(:
    • 如果您详细说明您的后续查询会更容易。
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2021-04-24
    相关资源
    最近更新 更多