[英]Apply arithmetic operation from json file to dataframe without using eval function
I have json file contains arithmetic operation list to apply in dataframe columns, I used eval function, but i could not use eval function due to security issue, how can apply arithmetic operation from json file without using eval function my df function will be like the below table: I have json file contains arithmetic operation list to apply in dataframe columns, I used eval function, but i could not use eval function due to security issue, how can apply arithmetic operation from json file without using eval function my df function will be like the下表:
a一个 | b b | c c | d d |
---|---|---|---|
10 10 | 20 20 | 40 40 | 25 25 |
15 15 | 10 10 | 35 35 | 10 10 |
25 25 | 20 20 | 30 30 | 100 100 |
100 100 | 15 15 | 35 35 | 20 20 |
20 20 | 25 25 | 25 25 | 15 15 |
10 10 | 25 25 | 45 45 | 30 30 |
10 10 | 20 20 | 40 40 | 25 25 |
10 10 | 20 20 | 40 40 | 25 25 |
json_ops_list= {"1":"a/b",
"2":"a+b+c",
"3": "(a-b)/(b+d)",
"4":"(a-b)/(b*d+c)"}
def calculations(df, json_ops_list):
final_df = pd.DataFrame()
for i in json_ops_list:
col_name = i + '_final'
final_df[col_name] = df.eval(i)
return final_df```
I think security problem is with python eval
, in pandas is no this problem :我认为安全问题是 python eval
,在 pandas 没有这个问题:
Neither simple nor compound statements are allowed.既不允许简单也不允许复合语句。 This includes things like for, while, and if.这包括诸如 for、while 和 if 之类的内容。
Your solution is necessary change for dictionary:您的解决方案是字典的必要更改:
json_ops_d= {"1":"a/b",
"2":"a+b+c",
"3": "(a-b)/(b+d)",
"4":"(a-b)/(b*d+c)"}
def calculations(df, d):
final_df = pd.DataFrame()
for k, v in d.items():
col_name = k + '_final'
final_df[col_name] = df.eval(v)
return final_df
df = calculations(df, json_ops_d)
print (df)
1_final 2_final 3_final 4_final
0 0.500000 70 -0.222222 -0.018519
1 1.500000 60 0.250000 0.037037
2 1.250000 75 0.041667 0.002463
3 6.666667 150 2.428571 0.253731
4 0.800000 70 -0.125000 -0.012500
5 0.400000 80 -0.272727 -0.018868
6 0.500000 70 -0.222222 -0.018519
7 0.500000 70 -0.222222 -0.018519
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.