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

How to update a value of a cell of a dataframe using the value of two cells below?

I have the following dataframe (created for an example):

In [2]: df
Out[2]:
   A  B
0  1  2
1  1  3
2  4  6

Assuming that this is a long dataframe, whenever there is a value of 2 in row B, I need to replace that value with the value that is two cells below that.

I tried:

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

for val in df['B']:
    if val == 2:
        df['B'] = df.B.shift(-2)

But I get:

    A   B
0   1   6.0
1   1   NaN
2   4   NaN

And I need:

Out[2]:
   A  B
0  1  6
1  1  3
2  4  6

Does anyone have suggestions for leaving rows that do not equal ‘2’ unchanged?

>Solution :

Then we just need to assign it with shift

df.loc[df['B'].eq(2),'B'] = df.B.shift(-2)
df
Out[458]: 
   A    B
0  1  6.0
1  1  3.0
2  4  6.0
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