chirag
chirag

Reputation: 173

Make a new Dataframe column based on key-value pair from a dictionary and an existing column

I have a dictionary:

acc_details = [{"account_number":100, "account_id":32}, {"account_number":32, "account_id":121},{"account_number":232, "account_id":12}, {"account_number":423, "account_id":56}]

and a Dataframe:


     transaction_value  account_number  ... fulfilment_date  tax_date
0                -2600            6827  ...             NaT       NaT
1               -21510            6830  ...             NaT       NaT
2               -83460            6825  ...             NaT       NaT
3                -2336            6650  ...             NaT       NaT
4               -65000            6303  ...             NaT       NaT
...                ...             ...  ...             ...       ...

I want to insert account_id which is in the dictionary in Dataframe as a new column based on the account_number which is already present in the Dataframe. Account_number is already a column in Dataframe. But I want to put those account_ids which belong to specific account_numbers. Data of which is given in the dictionary. An appropriate account_id should be inserted based on the associated account number.

I have tried a lot of things but failed to make any difference. Also, I have no experience with Dataframe so any help would be great.

Upvotes: 0

Views: 74

Answers (1)

Ligon Liu
Ligon Liu

Reputation: 76

Assuming you are using pandas dataframe. What you want to do is a dataframe merge, also called "left join" in the relational database world.

Suppose your original dataframe is called df

acc_details_df = pd.DataFrame(acc_details)

df_with_acc_id = df.merge(acc_details_df,on='account_number',how='left')

df_with_acc_id will carry the account_id column associated with account_number.

Upvotes: 1

Related Questions