Home > Net >  Pandas replacing subset of column values with another column based on index
Pandas replacing subset of column values with another column based on index

Time:06-09

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

    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 :)

CodePudding user response:

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
  • Related