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

loop over loc shift(-i) and repalce q(i) columns to np.nan [pandas]

how do I loop this in pandas instaed of writning 44 times?

df.loc[(df['id']!=df['id'].shift(-1)),['q1']]=np.nan
df.loc[(df['id']!=df['id'].shift(-2)),['q2']]=np.nan
df.loc[(df['id']!=df['id'].shift(-3)),['q3']]=np.nan

>Solution :

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

You should use a for loop, which will substitute in a new value for i each time. I’ve done it up to 3 (as per your example), but from you question, I think this should go to 44.

for i in range(1, 3):
    df.loc[(df['id']!=df['id'].shift(-i)),['q' + str(i)]]=np.nan
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