[英]Apply a rolling function with multiple arguments on a DataFrame
Let's say I have the following dataframe: 假设我有以下数据框:
df = pd.DataFrame({"quantity": [101, 102, 103], "price":[12, 33, 44]})
price quantity
0 12 101
1 33 102
2 44 103
I have been struggling to find how to apply a rolling complex function on it. 我一直在努力寻找如何在其上应用滚动复杂函数的方法。
For simplicity, let's assume this function f
is just the product of quantity
and price
. 为简单起见,让我们假设此函数
f
只是quantity
和price
的乘积。 In this case, how do I apply this function on a rolling window of size 1
, with a scaling parameter, say: 在这种情况下,如何在具有缩放参数的大小为
1
的滚动窗口上应用此功能,例如:
scaling = 10
such that the resulting dataframe would be: 这样结果数据框将是:
price quantity value
0 12 101 NaN
1 33 102 12120.0
2 44 103 33660.0
with value[i] = price[i-1]*quantity[i-1]*scaling
value[i] = price[i-1]*quantity[i-1]*scaling
I have tried: 我努力了:
def f(x,scaling):
return x['quantity']*x['price']*scaling
df.rolling(window=1).apply(lambda x: f(x,scaling))
and 和
def f(quantity,price,scaling):
return quantity*price*scaling
df.rolling(window=1).apply(lambda x: f(x['quantity'],x['price'],scaling))
Could you please help me fixing this without doing a simple: 你能帮我解决这个而不做一个简单的:
df['value'] = df['quantity'].shift(1)*df['price'].shift(1)*scaling
? ?
Assuming what you want is indeed value[i] = price[i-1] * quantity[i-1] * scaling
, then: 假设您想要的确实是
value[i] = price[i-1] * quantity[i-1] * scaling
,则:
scaling = 10
df['value'] = df.shift(1).apply(lambda x: x['quantity'] * x['price'] * scaling, axis=1)
df DF
quantity price value
0 101 12 NaN
1 102 33 12120.0
2 103 44 33660.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.