Skip to content
Advertisement

iterrows() , if statement and assigning string to new column

I want to add some data to a dataframe to analyse stock price movements. I want to check, if a row is the narrowst range in 7 bars. Unfortunately I seem to be able to run through the df array and perform a basic check. But I can´t assign a string to a column when the If-Statement fulfilled.Any ideas what´s wrong? I am coming XL VBA and so far it´s still a little bit overwhelming in python/ pandas…

import pandas as pd
import numpy as np

path = '/Users/chri....in/Documents/Python_Script/dataset/'
df = pd.read_csv(path+'AAPL.csv')

df['SMA10'] = df['Close'].rolling(10).mean()
df['ADR20'] = ((df['High'].rolling(20).mean()/df['Low'].rolling(20).mean())-1)*100
df['ADR1'] = (df['High']/df['Low']-1)*100
df['Range'] = df['High']-df['Low']
df['NR7'] = 'na'

for i, row in df.iterrows():
    #Condition for defining NR7, 4
    if df.iloc[i]['Range'] < df.iloc[i-1]['Range']: 
        df.iloc[i, 'NR7'] = ['NR4'] ***#This doesn´t seem to work***

Advertisement

Answer

You don’t need any loop at all. You don’t need even df['NR7'] = 'na'.

Just create NR7 column the following way:

df['NR7'] = np.where(df.Range < df.Range.shift(), 'NR4', 'na')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement