【问题标题】:select data from table and compare with dataframe从表中选择数据并与数据框进行比较
【发布时间】:2019-06-24 19:33:08
【问题描述】:

我有一个这样的数据框

Name  age   city
John   31   London
Pierre 35   Paris
...
Kasparov 40 NYC

我想使用 sql 从 redshift 城市表中选择数据,其中城市包含在数据框的城市中

query = select * from city where ....

你能帮我完成这个查询吗?

谢谢

【问题讨论】:

  • 你是用Python查询redshift吗?
  • 是的,我使用 python,jupyter

标签: python sql pandas dataframe amazon-redshift


【解决方案1】:

Jeril 的回答正朝着正确的方向发展,但并不完整。 df.unique() 结果不是它的系列的字符串。您的 where 子句中需要一个字符串

# create a string for cities to use in sql, the way sql expects the string
unique_cities = ','.join("'{0}'".format(c) for c in list(df['city'].unique()))

# output 
'London','Paris'

#sql query would be
query = f"select * from city where name in ({unique_cities})"

以上代码假设您使用的是 python 3.x

如果这能解决您的问题,请告诉我

【讨论】:

    【解决方案2】:

    您可以尝试以下方法:

    unique_cities = df['city'].unique()
    
    
    # sql query
    select * from city where name in unique_cities
    

    【讨论】:

    • 谢谢,但有一个问题:ProgrammingError: column "unique_cities" does not exist in city
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多