使用 pandas 计算列中的数学运算 [英] To calculate maths operation in a column using pandas
问题描述
我想使用python来获取CSV文件列中数学运算的最终值,我是否可以获取如下所示的值?
I would like to use python to get final values for maths operation in a column of a CSV file, may I know is it possible to get the value as below?
原始CSV:
Type Total
A 2+2
B (10/2)*5
C 5-2*3
预期输出:
Type Total
A 4
B 25
C -1
我已经尝试过搜索,但是对此一无所知...所有数据都是字符串形式,我试图转换为浮点数,但是由于数学运算,所以无法完成.
I have tried searching around but I could not get any idea on it... All data are in string, I tried to convert to float but due to the maths operation, so it cannot be done.
推荐答案
使用 pandas.eval
和不使用:
df['Total'] = pd.eval(df['Total'])
因为失败了,甚至超过了100行.
because failed if more like 100 rows.
如果只需要处理不丢失的值:
If need working only for not missing values:
mask = df['Total'].notna()
df.loc[mask, 'Total'] = df.loc[mask, 'Total'].apply(pd.eval)
如果可能,某些无法处理的值将使用自定义函数和 try-except
:
If possible some values which cannot be processed use custom function with try-except
:
print (df)
Type Total
0 A 2+2
1 B (10/2)*5
2 C 5-2*3
3 D NaN
4 E aaa
def func(x):
try:
return pd.eval(x)
except:
return x
df['Total'] = df['Total'].apply(func)
print (df)
Type Total
0 A 4
1 B 25
2 C -1
3 D NaN
4 E aaa
这篇关于使用 pandas 计算列中的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!