Group-by 用于生成多个变量的函数

Group-by for function that generates more than one variable

我在这里尝试使用技术分析库 (TA-lib) 计算一些分组项目: https://mrjbq7.github.io/ta-lib/

AROON等一些函数会生成两个变量,AR_UP和AR_DOWN。

如果不进行分组,我将使用以下内容:

dft['AR_UP'], dft['AR_DOWN'] = ta.AROON(dft['High'], dft['Low'], 14)

它会在 dft

中生成 AR_UP 和 AR_DOWN

但是,当我尝试应用分组时:

grouped=dft.groupby(["StockCode"]).apply(lambda x: (ta.AROON(x['High'], x['Low'], 14)))

这让我分组为:

StockCode
ABA    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
ABP    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
ABW    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
ACQ    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
ACU    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
                             ...                        
WTL    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
WZR    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
XPL    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
YBR    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
Z1P    ([nan, nan, nan, nan, nan, nan, nan, nan, nan,...
Length: 282, dtype: object

谁能告诉我哪里出错了?

我还想将其重新分配回原始数据框,例如:

grouped=(grouped.reset_index()
.groupby("StockCode",as_index=False)
.apply(lambda x: x.assign (AR_UP, AR_DOWN=(ta.AROON(x['High'], x['Low'], 14))))
.set_index('index') )

有可能吗?

谢谢!

这个有用吗?它适用于我的示例函数,但我无法安装该软件包。也许它也适用于您的功能。 groupby 后跟 apply 不适用于多个 return 值。

import numpy as np
import pandas as pd

dft={'High': range(11,21),
     'Low': range(1,11),
     'StockCode':np.append(np.repeat("A", 6), np.repeat("B", 4))}

dft=pd.DataFrame(dft)

dft=dft.sort_values("StockCode")

def aroon(x, y, n):
    return x/sum(x)*n, y/sum(y)*n

def my(x):
    a, b=aroon(x["High"], x["Low"], 2)
    return pd.DataFrame({"UP":a, "LOW":b})

grp=dft.groupby("StockCode").apply(lambda x: my(x))

dat=pd.concat([dft, grp], axis=1)

print dat

   High  Low StockCode       LOW        UP
0    11    1         A  0.095238  0.271605
1    12    2         A  0.190476  0.296296
2    13    3         A  0.285714  0.320988
3    14    4         A  0.380952  0.345679
4    15    5         A  0.476190  0.370370
5    16    6         A  0.571429  0.395062
6    17    7         B  0.411765  0.459459
7    18    8         B  0.470588  0.486486
8    19    9         B  0.529412  0.513514
9    20   10         B  0.588235  0.540541