我正在尝试用更快的方法替换迭代pandas数据帧的循环,但不确定如何将lambda与map一起应用以使其按预期工作。
我有一个价格数据框 - 例如:
open high low close
timestamp
2018-02-07 18:00:00 8341.0 8460.5 8255.0 8255.0
2018-02-07 19:00:00 8250.0 8270.0 8033.5 8179.0
2018-02-07 20:00:00 8183.0 8225.0 7972.5 8165.0
2018-02-07 21:00:00 8154.0 8289.0 8024.0 8078.0
对于每一行,我需要检查特定条件,这些条件当前写为:
if ((bars['close'].iloc[i - 1] > bars['close'].iloc[i - 5]) and
(bars['close'].iloc[i] < bars['close'].iloc[i - 4])):
如果满足条件,我需要增加一个计数器(mod 9)。
有人可以建议如何用更优雅和快速的解决方案替换循环检查这些条件吗?完整的代码段如下:
## Getting through an dataframe and calculating values
for i in range(0 + 6, size): #
bullish_flip = False
if setup_up == 9:
setup_up = 0 # restart count
nextbar_beyond = False
if ((bars['close'].iloc[i - 1] < bars['close'].iloc[i - 5])
and (bars['close'].iloc[i] > bars['close'].iloc[i - 4])):
bullish_flip = True
direction_up = True
if direction_down and bullish_flip:
#print 'Bullish flip 1', bars['close'].index[i]
direction_down = False
setup_up = 1
if direction_up and not bullish_flip:
if (bars['close'].iloc[i] < bars['close'].iloc[i - 4]):
setup_up = 1
nextbar_beyond = False
else:
setup_up += 1
输出示例:
open high low close td_setup \
timestamp
2018-01-30 19:00:00 9901.5 10251.0 9743.0 10120.0 1
2018-01-30 23:00:00 10105.0 10105.0 9512.0 9961.0 1
2018-01-31 03:00:00 9959.0 10093.0 9612.0 9983.5 1
2018-01-31 07:00:00 9988.0 10230.0 9933.5 10121.0 1
2018-01-31 11:00:00 10120.5 10327.0 9769.5 9876.0 1
2018-01-31 15:00:00 9877.0 10048.0 9719.5 9944.0 2
2018-01-31 19:00:00 9945.0 10112.5 9861.0 10046.5 1
2018-01-31 23:00:00 10046.0 10195.0 9983.0 10074.5 1
2018-02-01 03:00:00 10082.5 10167.0 9832.0 10035.5 1
2018-02-01 07:00:00 10043.0 10094.5 9331.5 9377.5 1
2018-02-01 11:00:00 9369.5 9567.0 9081.0 9310.0 2
2018-02-01 15:00:00 9312.5 9336.0 8875.0 8994.0 3
2018-02-01 19:00:00 8999.5 9234.0 8488.0 8889.0 4
2018-02-01 23:00:00 8891.5 9098.5 8536.5 8841.5 5
2018-02-02 03:00:00 8842.0 8914.5 8305.0 8530.0 6
2018-02-02 07:00:00 8527.5 8681.0 8085.0 8101.0 7
2018-02-02 11:00:00 8102.0 8826.5 7620.0 8578.5 8
2018-02-02 15:00:00 8648.0 9050.0 8464.0 8545.0 9