SQL where in clause using column in pandas dataframe

后端 未结 2 409
执笔经年
执笔经年 2021-01-18 12:48

I have a pandas dataframe that has a column of IDs. I need to run another sql query whose \'WHERE\' clause is dictated by all of the IDs in the aforementioned column.

<
相关标签:
2条回答
  • 2021-01-18 13:30

    for this to work for me I had to surround the list items with single quotes.

    str = ','.join(["'" + str(x) + "'" for x in df1['IDs'].tolist()])
    
    0 讨论(0)
  • 2021-01-18 13:32

    Convert the series to string

    str = ','.join([str(x) for x in df1['IDs'].tolist()])
    
    str
    '1,2,3,4,5,6'
    

    And, then insert it into the query string -

    qry = "Select id, SUM(revenue) AS revenue WHERE id IN (%s) Group by 1" % str
    
    qry
    'Select id, SUM(revenue) AS revenue WHERE id IN (1,2,3,4,5,6) Group by 1'
    
    0 讨论(0)
提交回复
热议问题