new_datascientist
new_datascientist

Reputation: 41

How to join two tables with the same values but with different column names in pandas

I have two tables:

reference_id reference_date price
112 2012-01-01 14.35
205 2012-03-02 10.02
325 2012-04-02 5.40
14 2012-06-20 7.68
ticket-reference_id quantity
112 2
205 4
325 7
14 5

I need to join the values of the reference_id and ticket_reference_id preserving the column names.

So that, I need to have the next result:

reference_id reference_date price quantity
112 2012-01-01 14.35 2
205 2012-03-02 10.02 4
325 2012-04-02 5.40 7
14 2012-06-20 7.68 5

I tried to do it with the next code but it doesnt join the values and it creates column reference_id and ticket-reference_id:

    result = df1.merge(right=df2, how='left', left_on='reference_id', right_on='ticket-reference_id', copy=False)  

Upvotes: 0

Views: 1200

Answers (1)

Henry Ecker
Henry Ecker

Reputation: 35636

Let's try renaming the column to match before merge:

result = df1.merge(df2.rename(columns={'ticket-reference_id': 'reference_id'}),
                   how='left',
                   on='reference_id', 
                   copy=False)
print(result)

result:

   reference_id reference_date  price  quantity
0           112     2012-01-01  14.35         2
1           205     2012-03-02  10.02         4
2           325     2012-04-02   5.40         7
3            14     2012-06-20   7.68         5

Upvotes: 2

Related Questions