-1

Can you please advise where my code is wrong. Why am I getting this error mesg-

Reliance ['long_position'] = np.nan
for x in range (len (Reliance)):
    if Reliance.Close[x] > Reliance.SMA20[x]:
        Reliance['long_position'][x] = 1
    if Reliance.Close[x] <= Reliance.SMA20[x]:
        Reliance['long_position'][x] = 0

I am calculating SMA20 and Close in other section of code. Warning: A value is trying to be set on a copy of a slice from a DataFrame

See below picture for more details please.

enter image description here

Mohit Garg
  • 61
  • 5

1 Answers1

0

The problem here is with the indexing. In pandas, you are supposed to use loc or iloc for indexing.

Reliance ['long_position'] = np.nan
for x in range (len (Reliance)):
    if Reliance.Close.iloc[x] > Reliance.SMA20.iloc[x]:
        Reliance['long_position'].iloc[x] = 1
    if Reliance.Close.iloc[x] <= Reliance.SMA20.iloc[x]:
        Reliance['long_position'].iloc[x] = 0

According to the documentation, the preferred way is as such:

Reliance.iloc[x, 'long_position'] = 0

Pandas indexing

Setting with copy