1

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.

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.