jeudi 16 avril 2020

Creating a New DataFrame Column and Filling it with an If Statement - Python

The desired outcome would be to have a new column with header 'xOver', whereby the values within xOver are determined by an if statement.

The values of xOver will either be: 1, 2, or NaN.

Value will be 1 if: data['Close'] > data['sma_5'] and data['Close'][-1] < data['sma_5']

Value will be NaN if that criteria is not satisfied.

Value will be 2 if another if and statement criteria is fulfilled (but for simplicity we can just ignore that for the purposes of solving this problem).

This is the data frame, which is called: data. enter image description here

This is the code I have tried thus far:

#
def xOver(data):

    if data['Close'] > data['sma_5'] and data['Close'][-1] < data['sma_5']:
        return 1
    else:
        np.nan

data['xOver'] = xOver
#

Which returns this: enter image description here

Aucun commentaire:

Enregistrer un commentaire