我想将自己的多参数函数应用于一个数据帧(或其中的一个系列),使用数据帧条目作为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')
我希望能够通过我自己的多参数函数的任何参数传递数据帧(或序列)的列。 有没有一种简单/直观(非黑客式)的方法?
如果我理解正确,你只需要:
熊猫系列可以乘/除/取常数的幂,返回相同大小的系列。你知道吗
在更复杂的场景中,当标量操作不够时,也可以将其编写为:
这里
axis=1
告诉Pandas将此函数应用于行而不是列(默认)要将此函数应用于elementwise,可以改用
df.appymap
:但是,如果
my_func
或其输入可以调整为使用向量,则速度将大大加快:相关问题 更多 >
编程相关推荐