python - Pandas:应用一个以列和变量作为参数的函数

标签 python python-3.x pandas dataframe apply

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

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

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)

感谢您的帮助!

最佳答案

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

def DummyFunction2(row, threshold):
    return row['a']*row['b']*threshold

df['Dummy2'] = df.apply(DummyFunction2, threshold=2, axis=1)

关于python - Pandas:应用一个以列和变量作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50071669/

相关文章:

Python Pandas : How to split a sorted dictionary in a column of a dataframe

python - Pandas Dataframe - 根据索引位置计算值

python - 删除字符串python中的utf-8文字

python-3.x - 如何修复Python中的 "Query'对象没有属性 'to_dict"错误?

xml - 无法在 xml 中找到具有命名空间的元素

python - 在 Python 中计算 e

python - 根据 Pandas 中的参数将列的值更改为 1 或 0

python - 如何连接来自 3 个小整数的字节以生成由 Python 中的这些字节表示的更大数字?

python - 检查非 root 用户是否可以访问路径

python - python列表中值的有效比较