1

My following query works and returns me a Dataframe subset containing only rows containing James's records.

pat_db.query('pat_medical_records == "James"')

However, I need to retrieve the information for thousands of patients. So I am trying to assign a variable name "a" and pass it over to the above line. Here I am getting errors.

a = James
pat_db.query('pat_medical_records == a')
UndefinedVariableError: name 'a' is not defined

I then tried assigning "a" manually:

a = "James"
pat_db.query('pat_medical_records == a')
UndefinedVariableError: name 'a' is not defined

What am I missing?

1
  • pat_db.query('pat_medical_records == @a') should do the trick Commented Jul 26, 2017 at 19:13

2 Answers 2

2

You can use str.format to specify placeholder strings for insertion:

a = ... # example; a = "James"    
pat_db.query('pat_medical_records == "{}"'.format(a))
Sign up to request clarification or add additional context in comments.

4 Comments

Hello I tried your suggested approach. However I am still getting an error. Using a="James Holt" SyntaxError: invalid syntax
@continuous_learner I figured it out. Double quotes were missing. Check my edit?
Worked perfectly! Thank you.
@continuous_learner Glad to know. Do consider looking at MaxU's answer though, that's a good one to use if it fits your use case (I didn't even know that existed!).
1

Try this:

my_list = ['James','Joe',...]
pat_db.query('pat_medical_records in @my_list')

You may want to read this great Pandas documentation with lots of useful examples

Demo:

In [81]: df = pd.DataFrame({'name': np.random.choice(['aaa','bbb','ccc','ddd','eee'], 20),
                            'age':np.random.randint(5, 99, 20)})

In [82]: df
Out[82]:
    age name
0    50  aaa
1    60  ccc
2    93  ddd
3    40  aaa
4    66  ddd
5    98  eee
6    95  eee
7    42  eee
8    53  bbb
9    74  ddd
10   93  ccc
11   76  ccc
12   74  aaa
13   74  eee
14   83  ddd
15   42  ddd
16   51  ccc
17   84  bbb
18   37  eee
19   24  aaa

In [83]: flt = ['aaa', 'eee']

In [84]: df.query("name in @flt")
Out[84]:
    age name
0    50  aaa
3    40  aaa
5    98  eee
6    95  eee
7    42  eee
12   74  aaa
13   74  eee
18   37  eee
19   24  aaa

1 Comment

Thank you for the answer. I appreciate the link as well.

Your Answer

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