Python Pandas query function

Viewed 198
for state in sample_states:
    state_df = df.query("Province_State == state").sum()

How can assign values to "state" just so the computer can read what I am referring to when I am going through a list called "sample_states"?

2 Answers

Use '@', per docs:

for state in sample_states:
    state_df = df.query("Province_State == @state").sum()

Using fstring (Python 3.6+):

for state in sample_states:
    state_df = df.query(f"Province_State == {state}").sum()

The syntax for fstring is fairly simple, just add f before any string, and then just add {...} over any variable.

Or just use the old "String formatter" (Python 2.6+ -> but introduced since python 3):

for state in sample_states:
    state_df = df.query(f"Province_State == {}".format(state)).sum()
Related