0

I have 2 dataframes and I want to add a new column to one of my dataframes from another dataframe '''

(df1)                            
Id   height  ...                 
12   190
13   180
34   173

. . .

(df2)
Id     amount  ...
12      234
15      256
13      248

. . .

''' how can I add a column "amount" to df1 that contains the value amount of df2 for each Id of df1. the size of df1 and df2 are not equal

1
  • df.join(df1.set_index('Id'), on='Id') Commented Oct 19, 2019 at 9:43

2 Answers 2

2

You can merge the two DataFrames on the Id column and then assign the resulting amount column to your first df:

import pandas as pd

df1 = pd.DataFrame(
    {"Id": [12, 13, 34], "height": [1, 2, 3]}
)
df2 = pd.DataFrame(
    {"Id": [12, 15, 13], "amount": [4, 5, 6]}
)

df1["amount"] = df1.merge(df2, on="Id")["amount"]

Result:

>>> print(df1)

   Id  height  amount
0  12       1     4.0
1  13       2     6.0
2  34       3     NaN
Sign up to request clarification or add additional context in comments.

Comments

0

Id Id is index column then you can use update method to do that

df1 = pd.DataFrame([[12, 190.0], [13, 180.0], [34, 173.0]], columns=('Id', 'height')).set_index("Id")

df2 = pd.DataFrame([[12, 234.0], [15, 256.0], [13, 248.0]], columns=('Id', 'amount')).set_index("Id")

df1["amount"] = np.nan
df1.update(df2, overwrite=True)
print(df1)

Result

    height  amount
Id                
12   190.0   234.0
13   180.0   248.0
34   173.0     NaN

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.