mtr_007
mtr_007

Reputation: 69

Getting keyerror:0 in pandas

In this data a new column is added with values varying from other columns.A keyerror: 0 shows up when I run this code even though I am not accessing a value that does not exist in the dataset.

   df['Action']=np.nan
   for i in range(len(df)-1):
        if df['Close Price'][i] < df['Close Price'][i+1]:
            df['Action'][i] = 1
        elif df['Close Price'][i] >= df['Close Price'][i+1]:
            df['Action'][i] = -1
    df = df.dropna()
    df

The error shows up in if df['Close Price'][i] < df['Close Price'][i+1]: this line of code.

Upvotes: 0

Views: 291

Answers (1)

Shantanu singh
Shantanu singh

Reputation: 82

this is not the correct way df['Close Price'][i] < df['Close Price'][i+1]: of getting ith row value of a specific column in pandas do

if df['Close Price'].iloc[i]< df['Close Price'].iloc[i+1] :

Upvotes: 1

Related Questions