我想应用到每个groupby对象的函数是ATR函数,它接受三个ndarrays并返回一个dataframe对象。我也想将结果放入原始数据框的新列中。这是我写的代码:
# the original dataframe:
col1 col2 col3 group
4762.1 4762.9 4762.9 1
4762.3 4762.1 4762.9 2
4762.3 4762.9 4762.1 1
4762.7 4762.5 4762.5 2
4762.5 4762.5 4762.5 1
... ... ... ...
def get_atr(df):
return ta.ATR(df['col1'].values, df['col2'].values, df['col3'].values)
df['atr'] = df.groupby('group').apply(get_atr)
预期结果应该是
col1 col2 col3 group atr
4762.1 4762.9 4762.9 1 (the result)
4762.3 4762.1 4762.9 2 (the result)
4762.3 4762.9 4762.1 1 (the result)
4762.7 4762.5 4762.5 2 (the result)
4762.5 4762.5 4762.5 1 (the result)
... ... ...
但是我得到所有NaN值
您可以尝试在函数中创建新列:
def get_atr(x):
x['atr'] = ta.ATR(x['col1'].values, x['col2'].values, x['col3'].values)
return x
df = df.groupby('group').apply(get_atr)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句