How to merge DataFrames by index and selected columns at the same time?

Viewed 64

I have two Pandas DataFrame that look like this:

dfA:

              A     B        C      x   y
date                    
2017-05-04  7.19    3.77    100.0   15  A
2017-05-05  7.19    3.77    100.0   15  B
2017-05-06  9.04    4.75    80.0    5   A
2017-05-07  9.04    4.75    80.0    5   B
2017-05-07  8.04    4.22    90.0    5   C
... ... ... ... ... ...

284 rows × 5 columns

dfB:

I want to merge it with another DataFrame that also has dates as indexes and columns x and y.

When I'm using:

pd.merge(dfA, dfB, left_index=True, right_index=True)

It's making new columns with x and y values and I want to merge it by index, x, and y.

1 Answers

try:

columns_to_use=dfA.columns.difference(dfB.columns)

db=pd.merge(dfA, dfB[columns_to_use],left_index=True, right_index=True, how='outer')

Beware of selecting appropriately the 'how' parameter, according to what you want to do.

Related