Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Warning mesg

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading