1

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.

7
  • 1
    Would you elaborate on the "WHERE clause of my query"? Commented Sep 29, 2021 at 19:33
  • Which part are you having trouble with - selecting a column? Commented Sep 29, 2021 at 19:35
  • Does select columns based on columns names containing a specific string in pandas anser your question? Commented Sep 29, 2021 at 19:36
  • 2
    See these answers. To convert a pandas Series to list, use df["ID"].tolist() Commented Sep 29, 2021 at 19:37
  • @zabop, I edited my question, hopefully that made it clear Commented Sep 29, 2021 at 19:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.