Pandas中的“.apply()”到第k个参数

2024-09-30 22:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

只有当我将dataframe作为第一个参数传递时,它似乎才起作用。我希望能够通过其他参数之一传递数据帧。你知道吗


# 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')

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


Tags: columnsthe数据函数dataframedf参数my
1条回答
网友
1楼 · 发布于 2024-09-30 22:17:59

如果我理解正确,你只需要:

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

熊猫系列可以乘/除/取常数的幂,返回相同大小的系列。你知道吗

在更复杂的场景中,当标量操作不够时,也可以将其编写为:

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

这里axis=1告诉Pandas将此函数应用于行而不是列(默认)

要将此函数应用于elementwise,可以改用df.appymap

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

但是,如果my_func或其输入可以调整为使用向量,则速度将大大加快:

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

相关问题 更多 >