pandas.eval() function in Python
This method is used to evaluate a Python expression as a string using various back ends. It returns ndarray, numeric scalar, DataFrame, Series.
Syntax : pandas.eval(expr, parser=’pandas’, engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False)
Arguments :
- expr : str or unicode. The expression to evaluate. This string cannot contain any Python
- parser : string, default ‘pandas’, {‘pandas’, ‘python’}.
- engine : string or None, default ‘numexpr’, {‘python’, ‘numexpr’}
- truediv : bool, optional, Whether to use true division, like in Python >= 3
- level : int, optional, The number of prior stack frames to traverse and add to the current scope. Most users will **not** need to change this parameter.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
import pandas
print (pandas. eval ( "2+3" ))
print (pandas. eval ( "2+3*(5-2)" ))
|
Output :
5
11
Example 2 :
Python3
import pandas
data = pandas.DataFrame({
"Student" : [ "A" , "B" , "C" , "D" ],
"Physics" : [ 89 , 34 , 23 , 56 ],
"Chemistry" : [ 34 , 56 , 98 , 56 ],
"Math" : [ 34 , 94 , 50 , 59 ]
})
display(data)
data[ 'Total' ] = pandas. eval ( "data.Physics+data.Chemistry+data.Math" )
display(data)
pandas. eval ( "Avg=data.Total/3" ,target = data,inplace = True )
display(data)
|
Output :
Last Updated :
14 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...