0

In my program, I want the user to be able to pass a string as a condition. For example, if the user input is "col(X) | col(Y)", I would like this string to be the filter condition in the filter function of a Dataframe. So an example will be like this:

condition = "col(X) | col(Y)"
dataFrame.filter(condition)

I saw on the documentation that I need an Expr to pass in the filter, but how can I transform a string to an Expr?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Zorp
  • 75
  • 5

1 Answers1

1

You can use eval(), builtin-function from Python like so:

condition = "col(X) | col(Y)"
dataFrame.filter(eval(condition))
Coderio
  • 429
  • 2
  • 9
  • Didn't thought it will work, thanks ! – Zorp May 13 '22 at 20:48
  • Did work for me with the latest version of polar. Failed with error `NameError: name 'col' is not defined` – Chitral Verma Jun 04 '22 at 13:59
  • @ChitralVerma, if you have not directly imported `col` from `polars`, then you will get a `NameError`. Therefore, if you do the usual `import polars as pl`, then your string predicate would need to be `"pl.col(X) | pl.col(Y)"`, for example. – Chuck Daniels Jan 15 '23 at 13:17