Home > Software engineering >  Reagrding new column in dataframe and getting keyerror
Reagrding new column in dataframe and getting keyerror

Time:06-18

this is my code

for i in range(len(df)-1):
    df['ot'].iloc[i]=(df['Open'].iloc[i]-df['Open'].iloc[i 1])/df['Open'].iloc[i 1]
print(df['ot'])

Here the ot is new column just created and open is dervied in dataframe, while I try to print ot after assigning that to the formula I get keyerror.

CodePudding user response:

Replace your loop by vectorization:

df['ot'] = df['Open'].diff(-1) / df['Open'].shift(-1)
print(df)

# Output
   Open    ot
1     2 -0.50  # (2 - 4) / 4 = -0.5
2     4  1.00  # (4 - 2) / 2 = 1
3     2 -0.75  # (2 - 8) / 8 = -0.75
4     8   NaN

CodePudding user response:

It looks like pct_change:

df['ot'] = df['open'].pct_change(-1)

Using @Corralien's example:

   Open    ot
0     2 -0.50
1     4  1.00
2     2 -0.75
3     8   NaN
  • Related