gpt4 book ai didi

python - 将具有多个参数的函数应用于 pandas groupby 对象

转载 作者:行者123 更新时间:2023-12-01 08:51:23 56 4
gpt4 key购买 nike

以下是我的数据框的样子:

  symbol      time    open    high     low   close
0 AAPL 09:35:00 219.19 219.67 218.38 218.64
1 AAPL 09:40:00 218.63 219.55 218.62 218.93
2 AAPL 09:45:00 218.91 219.09 218.27 218.44
3 AAPL 09:50:00 218.44 218.90 218.01 218.65
4 AAPL 09:55:00 218.67 218.79 218.08 218.59
5 AAPL 10:00:00 218.59 219.20 218.16 219.01

我正在尝试应用 talib 包中的函数,该函数采用两个参数:highlow。以下是我的尝试,它返回所有 NaN:

import pandas as pd
import numpy as np
import talib as ta

def f(x):
return ta.SAR(df.high, df.low, acceleration=0.05, maximum=0.2)

df['PSAR1'] = df.groupby(['symbol']).apply(f)

但是,该函数在没有 groupby 子句的情况下也可以正常工作,并返回以下数字:

df['PSAR2'] = ta.SAR(df.high,df.low, acceleration=0.05, maximum=0.2)

symbol time open high low close PSAR1 PSAR2
0 AAPL 09:35:00 219.190 219.670 218.380 218.640 NaN NaN
1 AAPL 09:40:00 218.630 219.550 218.620 218.930 NaN 218.380000
2 AAPL 09:45:00 218.910 219.090 218.270 218.440 NaN 219.550000
3 AAPL 09:50:00 218.440 218.900 218.010 218.650 NaN 219.550000
4 AAPL 09:55:00 218.670 218.790 218.080 218.590 NaN 219.396000
5 AAPL 10:00:00 218.590 219.200 218.160 219.010 NaN 219.257400

使用多个参数的applygroupby我做错了什么?

编辑:在 @bsmith89 的帮助下,以下工作成功了。

def f(df):    
return pd.DataFrame(ta.SAR(df.high, df.low, acceleration=0.05, maximum=0.2),columns= ['PSAR'])
y = df.groupby(['symbol']).apply(f)

df['PSAR'] = y.PSAR.reset_index(drop=True)

最佳答案

您已编写函数以将 x 作为参数,但随后对 df 进行操作。

我还没有测试过,但尝试重写为

def f(df):    
return ta.SAR(df.high, df.low, acceleration=0.05, maximum=0.2)

关于python - 将具有多个参数的函数应用于 pandas groupby 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53094886/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com