0

I have been using the following type of query + pandas code for different types of projects, and I am trying to find ways to do as much as possible directly in SQL instead:

import mysql.connector
list = [10,15]
sql = "select value, employee_id from employee_table"
df = pd.read_sql(sql,conn)
df_new = df.employee_id.isin(list)

So the above code would select only the salary for the employee_id of 10 and 15. In SQL, it would look like this:

select value, employee_id
from employee_table
where employee_id in (10,15) 

My question is how can I do the above query in python with a python list? I am using Mysql if it is of importance.

kyle
  • 691
  • 1
  • 7
  • 17
MathiasRa
  • 825
  • 2
  • 12
  • 24
  • Would be helpful to know which MySQL driver you are using. Generally, you could build a query statement with the appropriate amount of placeholders for bind variables. [This answer](https://stackoverflow.com/a/589416/4134674) should give you a general idea how to build that statement. You can then pass your list in the `params` argument to [`pandas.read_sql`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html#pandas-read-sql) for safe parameter substitution in the respective driver. – shmee Feb 26 '19 at 13:49

1 Answers1

0

If you want your output to be a pandas DataFrame that would have a similar output to your example SQL query, you can simply do:

df[df.employ_id.isin(list)]

Blazina
  • 1,206
  • 10
  • 13