英文:
Python - How to unpack a string?
问题
我需要将一组字符串解包成'variables'。这些字符串包含一个代码,用于筛选我从另一个API获取的数据框。这些字符串看起来像这样:
example_string = "Data[Data['Number'] > 2]"
example_string_2 = "Data[Data['Length'] <= 15]"
我需要将这些字符串视为已筛选的数据框。换句话说,我需要这些字符串的值像正常的代码一样工作。
我尝试使用星号进行解包,例如 *example_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.
答案1
得分: 3
根据这些表达式的确切语法,pandas.eval
可能适合您:
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))
英文:
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))
答案2
得分: 0
也许它有所帮助
example_string = 't1 = ' + example_string # 在可以看到结果的地方添加变量
exec(example_string)
example_string_2 = 't2 = ' + example_string_2
exec(example_string_2)
print(t1, t2)
英文:
Maybe it helps
example_string = 't1 = ' + example_string # add variables where you can see result
exec(example_string)
example_string_2 = 't2 = ' + example_string_2
exec(example_string_2)
print(t1, t2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论