harish bhavandla
harish bhavandla

Reputation: 21

How to copy data from a column of a data frame to another data frame using common column as a reference?

Assume,

Here, I want to get Phone numbers from column[Phone_no] into dataframe [df_addr],column['Phone'] using Account_No as reference.

I tried doing it and it is successfully extracting the values.

My Code:

if (len(df_addr>0)):
    for i in df_addr['Account_No'].index:
        v_acc_no = df_addr['Account_No'][i]
        mask = df_acc['Account_No'].isin([v_acc_no])
        if (len(df_acc[mask])>0):
           for x in df_acc[mask].index:
                 df_addr['Phone'][i] = df_acc['Phone_No'][x]

But, Is there any way to make this code even better?

Upvotes: 1

Views: 40

Answers (1)

zipa
zipa

Reputation: 27869

So you just need merge:

df_addr.merge(df_acc, on='Account_No')

You can add, how='left' to keep all the records from df_addr even though they don't have match in df_acc as the default is 'inner' (intersection).

As it was mentioned in comments, left_on and right_on should be used if the columns don't share the same name.

Upvotes: 1

Related Questions