如何遍历和检查前几行的条件?

时间:2019-04-09 16:47:03

标签: python python-3.x pandas

我正在尝试比较pandas数据框中的一列的值,检查条件是否成立,然后执行该操作。

我的日期设置如下: df

    Index  P_max  P_max_ind  RSI
0       0    0.0          0    0
1       1    0.0          0    0
2       2    0.0          0    0
3       3   11.8          3   81
4       4    0.0          0    0
5       5    0.0          0    0
6       6   11.5          6   75
7       7    0.0          0    0
8       8   11.0          8   80
9       9    0.0          0    0
10     10   12.0         10   80

以下是各列的说明:

  • 索引=就像序列号
  • P_max =最大值
  • P_max_ind = P_max值的索引
  • RSI = P_max的相对强度

我要根据以下条件创建两个新列Peak2和RSI2:

  1. 对于每个非零P_max点,它应检查先前的非零P_max点,并检查当前P_max是否>先前的P_max点。
  2. A。如果不满足,则检查当前P_max是否>前一个P_max点之前的非零P_max点 B.如果满意,则检查当前非零P_max点的RSI是否<先前非零P_max点的RSI。    一世。如果不满足条件,则转到第2.A点    ii。如果满足条件,则使用满足非零P_max点的值创建变量df.Peak2,使用对应Peak2点的RSI值创建变量df.RSI2。

我已经尝试过以下代码,但无法正常工作:

from datetime import date
from nsepy import get_history
import pandas as pd
import csv
import numpy as np
import scipy.stats as stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
import peakutils
from scipy.signal import argrelextrema

df = pd.read_excel('Test.xlsx', sheet_name='Test')
df['P_max'] = df['P_max'].replace(np.nan,0)
#df['P_max'] = df['P_max'].astype(np.int64)
df['P_max_ind'] = df['P_max_ind'].replace(np.nan,0)
df['P_max_ind'] = df['P_max_ind'].astype(np.int64)

i = 1

while i < len(df)-1:
    if df.P_max.shift(i)>0:
        if df.P_max > df.P_max.shift(i):
            if df.RSI > df.RSI.shift(i):
                df.Peak2 = df.P_max.shift(i)
                df.RSI2 = df.RSI.shift(i)
        else:
            i+1

预期输出如下:

    Index  P_max  P_max_ind  RSI  Peak2  RSI2
0       0    0.0          0    0    0.0     0
1       1    0.0          0    0    0.0     0
2       2    0.0          0    0    0.0     0
3       3   11.8          3   81    0.0     0
4       4    0.0          0    0    0.0     0
5       5    0.0          0    0    0.0     0
6       6   11.5          6   75    0.0     0
7       7    0.0          0    0    0.0     0
8       8   11.0          8   80    0.0     0
9       9    0.0          0    0    0.0     0
10     10   12.0         10   80   11.8    81

有人可以帮助我开发代码的流程和逻辑吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,则可以使用以下内容,这将比循环快得多:

    <input type="button" class="button" id="button2" value="2" onclick="click(this)">
    <input type="button" class="button" id="button3" value="3" onclick="click(this)">
    <input type="button" class="button" id="button4" value="4" onclick="click(this)">

function click(button){
    var buttonclicked = document.getElementById(button.id).value;
    firstbox.innerHTML = "Your Chosen button is: " + buttonclicked;
    button.disabled = true;
}