Python – How to unpack a string?

I have a specific case, i need to unpack a list of strings into a ‘variables’.
The strings contain a code which is filtering the dataframe that i get from another API.
The strings looks something like this:

example_string = "Data[Data['Number'] > 2]"
example_string_2 = "Data[Data['Length'] <= 15]"

What i need to do is to treat these strings like a filtered dataframes. So in other words i need these string values to work as a normal code.

I tried to unpack these with using the asterisk, fe. *example_string but it is not really working.

>Solution :

Depending on exactly what the syntax of those expressions are, pandas.eval might be the thing for you:

import pandas as pd

df = pd.DataFrame({'Number': [1, 2, 3, 4, 5],
                   'Length':  [5, 10, 15, 20, 25]})

ld = {'Data': df}
print(pd.eval("Data[Data['Number'] > 2]", local_dict=ld))
print(pd.eval("Data[Data['Length'] <= 15]", local_dict=ld))

Leave a Reply