📜  Python中的 pandas.eval()函数

📅  最后修改于: 2022-05-13 01:55:22.618000             🧑  作者: Mango

Python中的 pandas.eval()函数

此方法用于使用各种后端将Python表达式评估为字符串。它返回 ndarray、数值标量、DataFrame、Series。

以下是上述方法的实现以及一些示例:

示例 1:

Python3
# importing package
import pandas
  
# evaluate the expressions given
# in form of string
print(pandas.eval("2+3"))
print(pandas.eval("2+3*(5-2)"))


Python3
# importing package
import pandas
  
# creating data
data = pandas.DataFrame({
      "Student": ["A", "B", "C", "D"], 
    "Physics": [89,34,23,56], 
    "Chemistry": [34,56,98,56], 
    "Math": [34,94,50,59]
    })
  
# view data
display(data)
  
# adding new column by existing 
# columns evaluation
data['Total']=pandas.eval("data.Physics+data.Chemistry+data.Math")
  
# view data
display(data)
  
# adding new column by existing 
# columns evaluation
pandas.eval("Avg=data.Total/3",target=data,inplace=True)
  
# view data
display(data)


输出 :

5
11

示例 2:

Python3

# importing package
import pandas
  
# creating data
data = pandas.DataFrame({
      "Student": ["A", "B", "C", "D"], 
    "Physics": [89,34,23,56], 
    "Chemistry": [34,56,98,56], 
    "Math": [34,94,50,59]
    })
  
# view data
display(data)
  
# adding new column by existing 
# columns evaluation
data['Total']=pandas.eval("data.Physics+data.Chemistry+data.Math")
  
# view data
display(data)
  
# adding new column by existing 
# columns evaluation
pandas.eval("Avg=data.Total/3",target=data,inplace=True)
  
# view data
display(data)

输出 :