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 replacing subset of column values with another column based on index

hope it’s not a duplicated question, I tried to check other questions but didn’t find what I needed.

I have a dataframe df:

    a   b
0   6   4
1   5   6
2   2   2
3   7   4
4   3   6
5   5   2
6   4   7

and a second dataframe df2

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

    d
0   60
1   50
5   50
6   40

I want to replace the values in df[‘a’] with the values in df2[‘d’]but only in the relevant indices.

Output:

    a   b
0   60  4
1   50  6
2   2   2
3   7   4
4   3   6
5   50  2
6   40  7

All other questions I saw like this one referring to a single value, but I want to replace the values based on entire column.

I know I can iterate the rows one by one and replace the values, but I’m looking for a more efficient way.

Note: df2 does not have indices that are not in df. I want to replace all values in df2 with the values of df.

Thanks for the help 🙂

>Solution :

Simply use indexing:

df.loc[df2.index, 'a'] = df2['d']

output:

    a  b
0  60  4
1  50  6
2   2  2
3   7  4
4   3  6
5  50  2
6  40  7
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