【问题标题】:Pandas: apply a function with columns and a variable as argumentPandas:应用带有列和变量作为参数的函数
【发布时间】:2018-10-08 20:18:40
【问题描述】:

我正在尝试将一个具有多个参数的函数应用于数据帧,其中两个需要分配给数据帧的行,一个是变量(一个简单的数字)。

类似线程的变体适用于行:(与我的原始函数相比,所有函数都过于简单)

import pandas as pd

dict={'a':[-2,5,4,-6], 'b':[4,4,5,-8]}

df=pd.DataFrame (dict)
print(df)

def DummyFunction (row):
    return row['a']*row['b']
#this works:
df['Dummy1']=df.apply(DummyFunction, axis=1)

但是如何应用以下变体,我的函数接受一个附加参数(一个固定变量)?我似乎没有办法在 apply 方法中传递它:

def DummyFunction2(row, threshold):
    return row['a']*row['b']*threshold
# where threshold will be assigned to a number?
# I don't seem to find a viable option to fill the row argument below:
# df['Dummy2']=df.apply(DummyFunction2(row,1000), axis=1)

感谢您的帮助!

【问题讨论】:

    标签: python python-3.x pandas dataframe apply


    【解决方案1】:

    您可以将附加变量直接作为命名参数传递给pd.DataFrame.apply

    def DummyFunction2(row, threshold):
        return row['a']*row['b']*threshold
    
    df['Dummy2'] = df.apply(DummyFunction2, threshold=2, axis=1)
    

    【讨论】:

    • 嗨@jpp,你无法理解我有多感激。我在任何在线教程中都找不到关于此的任何内容。谢谢!
    猜你喜欢
    • 2012-08-24
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2021-12-17
    • 2012-04-18
    相关资源
    最近更新 更多