Python 如何将函数的字符串输出转换为输入或可运行的shell命令?
例如,我使用这段代码为mask获取一个值Python 如何将函数的字符串输出转换为输入或可运行的shell命令?,python,pandas,string,dataframe,return-value,Python,Pandas,String,Dataframe,Return Value,例如,我使用这段代码为mask获取一个值 def get_rule(path, column_names): mask = '' for index, node in enumerate(path): #We check if we are not in the leaf if index!=len(path)-1: # Do we go under or over the threshold ? i
def get_rule(path, column_names):
mask = ''
for index, node in enumerate(path):
#We check if we are not in the leaf
if index!=len(path)-1:
# Do we go under or over the threshold ?
if (children_left[node] == path[index+1]):
mask += "(df['{}']<= {}) \t ".format(column_names[feature[node]], threshold[node])
else:
mask += "(df['{}']> {}) \t ".format(column_names[feature[node]], threshold[node])
# We insert the & at the right places
mask = mask.replace("\t", "&", mask.count("\t") - 1)
mask = mask.replace("\t", "")
return mask
将给出错误:
KeyError: "(df['A']<= 0.12) & (df['B']> 0.07) & (df['C']<= 0.24) & (df['D']<= 4.0) & (df['A']> 0.92)"
您可能正在查找或函数。这些函数允许您以str
的形式运行动态python代码
例如:
>>> df[output]
exec("x = 1234") # executes x = 1234 (set value of x to 1234)
eval("2 + 3 * 5") # returns 17
因此,您可能希望这样使用它:
>>> output = get_rule(...)
>>> output
"(df['A']<= 0.12) & (df['B']> 0.07) & (df['C']<= 0.24) & (df['D']<= 4.0) & (df['A']> 0.92)"
eval(f"df[{output}]") # Can't use exec() here because it doesn't return value
您需要字符串格式的结果吗?在执行过程中只计算结果,而不是在字符串上使用eval或exec,可能会很容易。
eval(f"df[{output}]") # Can't use exec() here because it doesn't return value