熊猫在第k个参数中使用“ .apply()”

时间:2019-09-17 01:54:56

标签: python pandas dataframe

我想将自己的多参数函数应用于Pandas数据帧(或其中的一系列数据),并使用数据帧条目作为N参数函数中的第k个参数。

这似乎只有在我将数据框作为第一个参数传递时才有效。我希望能够通过其他参数之一传递数据框。


# A simple 3 argument function:
def my_func(a, b, c):
    return (a/b)**c

# Data-Frame:
d1 = {
    'column1': [1.1, 1.2, 1.3, ],
    'column2': [2.1, 2.2, 2.3, ]
}
df = pd.DataFrame(d1, index = [1, 2, 3])


# I can apply it fine if I pass the columns as the first argument i.e. "a":
df.apply(my_func, b=7, c=9)

# However, I am unable to pass the columns through arguments "b" or "c":
df.apply(my_func, a = 7, c = 9)

这将返回TypeError:(“ my_func()对于参数'a'”,“在索引列1处出现”具有多个值)

我希望能够通过我自己的多参数函数的任何参数传递数据框(或系列)的列。 有没有简单/直观(非黑客式)的方法?

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您需要做的就是:

my_func(df['column1'], b=7, c=5)

Pandas系列可以乘以/除以/以获得常数,返回相同大小的系列。

在更复杂的情况下,当标量运算不够用时,也可以将其写为:

df.apply(lambda row: my_func(row['column1'], b=7, c=5), axis=1)

此处axis=1告诉Pandas将此功能应用于行而不是列(默认)

要逐个应用此功能,可以改用df.appymap

df.applymap(lambda value: my_func(7, value, c=5)

但是,如果my_func或其输入可以调整为使用矢量,则将

my_func(np.ones(df.shape) * 7, df, c=5)