Windtalker
Windtalker

Reputation: 796

Use string variable in Python dataframe function

If I use

df.loc[(origFull['abc'] == 111)]

it will work of course.

Then

test = '(origFull[\'abc\'] == 111)'

df.loc[@test]

or

df.loc['@test']

Neither worked.

Upvotes: 0

Views: 193

Answers (3)

Reen
Reen

Reputation: 429

Take the quotes away when you define test.

Inside of loc you are essentially creating a boolean variable. So set test equal to that boolean and use it as a boolean index:

test = (origFull['abc'] == 111)

df.loc[test]

Upvotes: 1

Craig
Craig

Reputation: 4855

Maybe you are looking for the .query() method?

test = "abc == 111"
df.query(test)

Upvotes: 0

Taku
Taku

Reputation: 33714

A few things are wrong:

1: You want test to be a value(a boolean value to be exact), if you added single quotes around them, test turns into a string. Do this instead:

test = origFull['abc'] == 111

2: @ symbol isn't valid syntax for python, excepted when it's used for decorators. To use test as a variable, just write test without the @.

df.loc[test]

Upvotes: 1

Related Questions