Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading