基于多列计算公式的Pandas Dataframe - 但是不创建多个中间列

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

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

我一直在试图计算“真实范围”的公式,基于熊猫数据框包含股票行情历史。

公式如下:

TR = max [(high - low ), abs(high − close prev), abs ⁡(low − close prev)] 

我在数据帧中有high、low和close列。

当我尝试这样操作时,我得到了无效字符标识符错误,这不是很有帮助。我在下面的表达中尝试了许多改变和组合,但是没有成功。

^{pr2}$

我知道这可以通过三个独立的中间柱来实现,并且取其最大值。但是,我想避免同样的情况,直接去做。

有出路吗?


Tags: 数据close错误abs标识符历史字符tr
2条回答

concatmax一起使用:

df['TR'] = pd.concat([(df['high'] - df['low']), 
                      (df['high'] - df['adjclose'].shift(1)).abs(),
                      (df['low']  - df['adjclose'].shift(1))], axis=1).max(axis=1)

样本

^{pr2}$

细节

print (pd.concat([(df['high']-df['low']), 
                      (df['high'] - df['adjclose'].shift(1)).abs(),
                      (df['low'] - df['adjclose'].shift(1))], axis=1))
   0    1    2
0 -3  NaN  NaN
1 -3  4.0  7.0
2 -5  1.0  6.0
3  1  0.0 -1.0
4  3  2.0 -5.0
5  1  3.0  2.0

Numpy解决方案不同,因为行中NaN的最大值又是NaN

df['TR1'] = np.max(np.c_[(df['high']-df['low']), 
                        (df['high'] - df['adjclose'].shift(1)).abs(),
                        (df['low'] - df['adjclose'].shift(1))], axis=1)

print (df)
   adjclose  high  low  TR1
0         1     4    7  NaN
1         3     5    8  7.0
2         5     4    9  6.0
3         7     5    4  1.0
4         1     5    2  3.0
5         0     4    3  3.0

print (np.c_[(df['high']-df['low']), 
                        (df['high'] - df['adjclose'].shift(1)).abs(),
                        (df['low'] - df['adjclose'].shift(1))])

[[-3. nan nan]
 [-3.  4.  7.]
 [-5.  1.  6.]
 [ 1.  0. -1.]
 [ 3.  2. -5.]
 [ 1.  3.  2.]] 

可以通过以下方式实现:

df['TR']=list(map(max,zip((df['high']-df['low']), (df['high'] - df['adjclose'].shift(1)).abs(),(df['low'] - df['adjclose'].shift(1)))))

相关问题 更多 >