Python – 如何解包字符串?

huangapple go评论69阅读模式
英文:

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 = &quot;Data[Data[&#39;Number&#39;] &gt; 2]&quot;
example_string_2 = &quot;Data[Data[&#39;Length&#39;] &lt;= 15]&quot;

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({&#39;Number&#39;: [1, 2, 3, 4, 5],
                   &#39;Length&#39;:  [5, 10, 15, 20, 25]})

ld = {&#39;Data&#39;: df}
print(pd.eval(&quot;Data[Data[&#39;Number&#39;] &gt; 2]&quot;, local_dict=ld))
print(pd.eval(&quot;Data[Data[&#39;Length&#39;] &lt;= 15]&quot;, 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  = &#39;t1 = &#39; + example_string    # add variables where you can see result
exec(example_string)
example_string_2 = &#39;t2 = &#39; + example_string_2 
exec(example_string_2)
print(t1, t2)

huangapple
  • 本文由 发表于 2023年3月7日 22:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定