Xin Shen
Xin Shen

Reputation: 33

How to use loop variable inside pandas df.query()

How do I fix the following df.query line to stop getting the error msg: name 'z' is not defined.

I have data in 3 columns and wanna plot 3D polygons. I run a loop to pair up (X, Y), in which I try to use the loop variable, z, to screen one column:

zs = [20, 30, 40, 50, 60, 70]
for z in zs:
    ys = df.query('column1==z')['Column2']
    verts.append(list(zip(xs, ys)))

Upvotes: 3

Views: 3807

Answers (2)

azro
azro

Reputation: 54148

From your code, you may passe the value of z, not the sting "z", do thta with a formatted string for example or just concat the elements

ys = df.query(f'column1=={z}')['Column2']
ys = df.query('column1==' + str(z))['Column2']

But the slicing syntax is a bit more easy to use

ys = df[df.column1 == z]['Column2']

Upvotes: 4

Hamza
Hamza

Reputation: 6025

Use format strings:

zs = [20, 30, 40, 50, 60, 70]
for z in zs:
    ys = df.query(f'column1=={z}')['Column2']
    verts.append(list(zip(xs, ys)))

Upvotes: 0

Related Questions