如何将不带 single/double 引号的字符串传递给 Python 循环中的另一个函数

How to pass string without single/double quotes to another function in a loop in Python

我已经从决策树中提取了 1000 条规则并保存在数据框中。以下是示例规则

(age > 25) & (Tenure < 48)

现在我想检查 pandas 数据框 (Data_rules) 中有多少观察值遵循每个规则。基本上我想在应用上述规则后检查数据帧的长度。下面是我写的代码

for i in Data_rules.index: 
    temp = len(train[Data_rules['Rules'][i]]) 
    output.append(temp)

此代码向我抛出 'key error' 因为 Data_rules['Rules'][i] 将以字符串形式给出每个规则并以单引号开头,例如 '(age > 25) & (Tenure < 48)' 但我们需要通过不带引号的规则来训练数据集。谁能帮我解决这个问题。

这正是 DataFrame.query 的用途,这里有一个例子:

import pandas as pd

df = pd.DataFrame({"age": [10, 15, 20, 25, 30, 35], "Tenure": [1, 1, 1, 1, 50, 47]})
result = df.query("(age > 25) & (Tenure < 48)")

print(result)

输出:

   age  Tenure
5   35      47