Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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)))
like image 803
Xin Shen Avatar asked Jul 27 '26 07:07

Xin Shen


1 Answers

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']
like image 77
azro Avatar answered Jul 28 '26 19:07

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!