我正在构建一个网站,用户可以在其中绘制数据帧中的数据,并对这些数据应用过滤器,以便只绘制他们感兴趣的信息,如下所示

现在,我很难找到一种方法来获取用户在上面字段中输入的过滤器,并使用这些输入来过滤数据帧。由于用户可以创建无限数量的筛选器,因此我决定使用for循环来构建一个可执行字符串,该字符串在一个变量中包含所有筛选器,如下所示
column = (value selected in "Select Parameter", which corresponds to a column in the dataframe)
boolean = (value selected in "Select Condition" e.g., >, <, >= ect....
user_input = (value user inputs into field e.g., 2019 and Diabetes)
executable = 'df = df[df[' + column1 + '] ' + boolean1 + user_input1 + ' and ' + 'df[' + column2 + '] ' + boolean2 + user_input2 + ' and '.....
exec(executable)虽然此方法可以工作,但它使我的代码非常容易受到注入的攻击。有没有更好的方法来做这件事?
发布于 2021-02-18 15:22:23
您可以使用operator模块,它将运算符作为函数。您可以为a<b执行operator.lt(a,b)。只需将用户输入映射到操作符即可。
例如:
import operator
operator_map = {'<':operator.lt, '<=':operator.le, '>':operator.gt}然后可以创建一个过滤器,如下所示
import numpy as np
# Start with selecting all then `and` the filters
df_filter = np.ones((df.shape[0],),dtype=bool)
# Go through each user filter input
for ...:
df_filter = df_filter & operator_map[boolean](df[column], user_input)
filtered_df = df[df_filter]https://stackoverflow.com/questions/66253253
复制相似问题