在DataFram上应用具有多个参数的滚动函数

2024-04-25 14:28:04 发布

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

假设我有以下数据帧:

df = pd.DataFrame({"quantity": [101, 102, 103], "price":[12, 33, 44]})

    price   quantity
0   12      101
1   33      102
2   44      103

我一直在努力寻找如何应用一个滚动复杂的函数。你知道吗

为了简单起见,我们假设这个函数f只是quantityprice的乘积。在本例中,如何在大小为1的滚动窗口上应用此函数,并使用缩放参数,例如:

scaling = 10

这样产生的数据帧将是:

    price   quantity    value
0   12      101         NaN
1   33      102         12120.0
2   44      103         33660.0

value[i] = price[i-1]*quantity[i-1]*scaling

我试过:

def f(x,scaling):
    return x['quantity']*x['price']*scaling
df.rolling(window=1).apply(lambda x: f(x,scaling))

以及

def f(quantity,price,scaling):
    return quantity*price*scaling
df.rolling(window=1).apply(lambda x: f(x['quantity'],x['price'],scaling))

请你帮我解决这个问题,而不必做一个简单的:

df['value'] = df['quantity'].shift(1)*df['price'].shift(1)*scaling 

什么?你知道吗


Tags: 数据lambda函数dfreturnshiftvaluedef
1条回答
网友
1楼 · 发布于 2024-04-25 14:28:04

假设你想要的确实是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)

测向

    quantity    price   value
0   101         12      NaN
1   102         33      12120.0
2   103         44      33660.0

相关问题 更多 >