Sean
Sean

Reputation: 21

Python Pandas query function

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"?

Upvotes: 2

Views: 436

Answers (2)

Scott Boston
Scott Boston

Reputation: 153500

Use '@', per docs:

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

Upvotes: 1

MercyDude
MercyDude

Reputation: 914

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()

Upvotes: 0

Related Questions