编写一个 Python 程序在数据框中执行表式管道函数
pythonpandasserver side programmingprogramming更新于 2024/6/22 11:24:17
假设您有一个数据框,表式函数的结果是,
表式函数: Id Mark 0 6.0 85.0 1 7.0 95.0 2 8.0 75.0 3 9.0 90.0 4 10.0 95.0
解决方案
为了解决这个问题,我们将遵循下面给出的步骤 −
定义一个数据框
创建一个具有两个参数的用户定义函数 avg,并将结果返回为 (a+b/2)。它定义如下,
def avg(a,b): return (a+b/2)
应用 pipe() 函数执行表函数,第一个值为 avg(),第二个参数为 10,以计算所有数据框值的平均值。
df.pipe(avg,10)
示例
让我们检查以下代码以更好地理解 −
import pandas as pd
df = pd.DataFrame({'Id':[1,2,3,4,5],'Mark':[80,90,70,85,90]})
print("DataFrame is:\n",df)
print("Table wise function:")
def avg(a,b):
return (a+b/2)
print(df.pipe(avg,10))
输出
DataFrame is: Id Mark 0 1 80 1 2 90 2 3 70 3 4 85 4 5 90 Table wise function: Id Mark 0 6.0 85.0 1 7.0 95.0 2 8.0 75.0 3 9.0 90.0 4 10.0 95.0
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

