Home > Blockchain >  Use pandas series as input parameter
Use pandas series as input parameter

Time:09-30

I'm a R user trying to pick up Python. In R, I often used vectors to pass as arguments to SQL query. For example,

ID <- c(1,2,3,4,5)
df <- dbGetQuery(con, paste("select * from table where ID in (", ID, ")")

How can I achieve this in Python? I have a dataframe and would like to use one of its columns as the parameters. So with a dataframe like this,

data = {'ID': [1,2,3,4,5],
        'Value': [10,20,30,40,50]}
df = pd.DataFrame(data)

[Edit] So basically I need a string that would read "Select * from table where ID in (1,2,3,4,5)" except, instead of manually typing "1,2,3,4,5" I want to use parameters.

CodePudding user response:

OP are looking for something like

query = f"select * from table where ID in ({','.join(df['ID'].astype(str))})"

For more ways to create this query from list, one can also check this post provided by @Erfan in a comment.

  • Related