创建一个新的DataFrame列并使用If语句填充它-Python

时间:2020-04-16 13:19:03

标签: python pandas dataframe if-statement moving-average

期望的结果是使用标题为'xOver'的新列,从而xif中的值由if语句确定。

xOver的值将是:1、2或NaN。

如果满足以下条件,则值为1:data ['Close']> data ['sma_5']和data ['Close'] [-1]

如果不满足该条件,则值为NaN。

如果满足另一个if和statement条件,则值将为2(但为简单起见,为了解决此问题,我们可以忽略该值)。

这是数据帧,称为:数据。 enter image description here

这是我到目前为止尝试过的代码:

input:checked ~ button{
    display: none;
  }

<div  id="form">
    <section class="container">
        <form class="form">
            <section class="checkbox-control">
                <label for="personal-data-checkbox" class="checkbox-border">
                    <input type="checkbox"  id="personal-data-checkbox">
                </label>
                <label for="personal-data-checkbox" class="checkbox-label">
                    <span class="consent-message"></span>
                </label>
            </section>

            <section class="checkbox-control">
                <label for="cookie-checkbox" class="checkbox-border">
                    <input type="checkbox"  id="cookie-checkbox">
                </label>
                <label for="cookie--checkbox" class="checkbox-label">
                    <span> </span>
                </label>
            </section>

            <section class="buttons">
                <section class="confirm">
                    <button class="accept-all-button button">Agree to all</button>
                    <button class="confirm-button button hidden-button">Confirm</button>
                </section>
            </section>    
        </form>
    </section>
</div>

哪个返回: enter image description here

SPY.xlsx

enter image description here

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,解决方案是:

data['xOver'] = np.where((data['Close'].shift(+2) < data['sma_5'].shift(+1)) 
                         & (data['Close'].shift(+1) > data['sma_5'].shift(+1))
                         & (data['Close'] > data['sma_5'].shift(+1)),
                         data['sma_5'],np.nan)