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

Question:

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***
Asked By: Chris

||

Answers:

You got it right everywhere else…

df.iloc[i]['NR4'] = 'NR4'

When using iloc you can’t use the column names.

Also, unless you want to assign a list containing one element, don’t put square brackets around the string.

Answered By: s_pike

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')
Answered By: Valdi_Bo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.