【发布时间】:2021-06-20 15:12:15
【问题描述】:
我正在尝试计算值True 出现在我的pandas 数据框列的最后5 行中的次数。总共有200 行。我将使用这个计数 (emacount) 来验证并继续(比如说if count >=5)这样做..else..
我能想出的代码计算下面的所需输出。我使用相同的技术在 2 个if 语句中获得类似的计数,如下所示(因为这是在 2 列中检查 True 的条件,如果两列都有值 True,则返回值)
for now in range(len(df.index) - 15, len(df.index)):
if df['in_side'][now]:
if df['bb_side'][now]:
count = count + 1
else:
count = count + 0
else:
count = count - 1
这似乎正确地给出了count 的数量。
我尝试应用相同的逻辑来计算emacount,如下所示,但输出结果不如预期(它在-4 和4 之间波动)所需的输出是从0 开始,然后根据in_trend 列的最后5 行(行195 到199)中True 的数量,计算emacount(不同于0-5)每次更新数据帧(运行@ 987654343@)
我计算 emacount 和 count 的代码是:
count = 0
emacount = 0
for now in range(len(df.index) - 15, len(df.index)):
if df['in_side'][now]:
if df['bb_side'][now]:
count = count + 1
else:
count = count + 0
else:
count = count - 1
for now2 in range(len(df.index) - 5, len(df.index)):
if df['in_trend'][now2]:
emacount = emacount + 1
else:
emacount = emacount -1
下面是我的数据框
timestamp close p_diff ... bb_side emadiff in_trend
180 2021-06-20 14:39:00+05:30 35205.83 0.348388 ... True -17.065951 False
181 2021-06-20 14:42:00+05:30 35224.71 0.131215 ... True -13.642527 False
182 2021-06-20 14:45:00+05:30 35189.40 0.044197 ... True -15.706096 False
183 2021-06-20 14:48:00+05:30 35245.42 0.056861 ... True -8.875039 False
184 2021-06-20 14:51:00+05:30 35255.23 0.052819 ... True -7.095512 False
185 2021-06-20 14:54:00+05:30 35266.99 0.046941 ... True -5.299749 False
186 2021-06-20 14:57:00+05:30 35324.42 0.145489 ... True 0.674513 True
187 2021-06-20 15:00:00+05:30 35370.05 0.124836 ... True 4.955988 True
188 2021-06-20 15:03:00+05:30 35353.62 0.177176 ... True 2.919227 True
189 2021-06-20 15:06:00+05:30 35333.78 0.104324 ... True 0.751682 True
190 2021-06-20 15:09:00+05:30 35295.48 0.076508 ... True -2.967526 False
191 2021-06-20 15:12:00+05:30 35245.00 0.091845 ... True -7.492524 False
192 2021-06-20 15:15:00+05:30 35256.50 0.089293 ... True -5.683712 False
193 2021-06-20 15:18:00+05:30 35208.37 0.101059 ... True -9.726215 False
194 2021-06-20 15:21:00+05:30 34914.02 0.452258 ... True -36.833243 False
195 2021-06-20 15:24:00+05:30 34987.38 0.589260 ... True -26.338648 False
196 2021-06-20 15:27:00+05:30 34986.43 0.379041 ... True -23.920682 False
197 2021-06-20 15:30:00+05:30 34944.72 0.245694 ... True -25.614902 False
198 2021-06-20 15:33:00+05:30 34379.34 0.930663 ... False -77.021102 False
199 2021-06-20 15:36:00+05:30 34489.50 0.962524 ... False -59.194330 False
感谢您的光临。有一个安全和美好的一天:)
编辑 1:emacount 的计数取决于 in_trend 列。
在当前时间 15:06 emacount 应该有值 4 并且在当前时间返回 15:03 值 3 和 15:15 值应该是 2
编辑 2:如果我的帖子令人困惑,我很抱歉。 emacount 中的值将基于 in_trend 列。 in_trend 中的值 True 或 False 表示市场是上升趋势 (True) 还是下降趋势 (False)。因此,如果我想检查长期上升趋势,那么我将检查最后 5 个值(因此 >5 条件)。如果它们是真的,那么它就是上升趋势,即使任何一行是 False (计数
此函数会以 3 分钟的间隔重复,因此根据最后 5 行,我们可以确定长期上升趋势是否正在进行
所以根据以上数据,从 14:30 到 15:36 没有长期上升趋势,因为计数永远不会达到 5,也没有 5 个 True 一个接一个
【问题讨论】:
-
您的预期输出是什么样的?
-
嗨@HenryEcker。感谢您的帮助。假设现在时间是
15:06(第189行是最后一行199)然后emacount应该有值4并返回当前时间15:03值3和15:15值应该是2