I left join dataframe A to B based on a key. After merging, I see there was not any crecord on right dataframe that has the same key as the right dataframe, but the columns ffrom right table are still added. How to keep Pandas from adding new columns from right if there is not common records?
Asked
Active
Viewed 680 times
0
-
1Please see [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and provide a [mcve] for your issue, including some sample input, current output, and expected output – G. Anderson Jul 23 '19 at 16:28
1 Answers
0
It sounds like a left merge. Try below and see if it gives you the desired output. Also included right, inner and outer for some hands-on experience of the different merges.
import pandas as pd
df1 = pd.DataFrame({'A': ['foo', 'bar', 'baz'],
'B': [1, 2, 3]})
df2 = pd.DataFrame({'A': ['foo', 'bar', 'trumpet'],
'C': [4, 5, 6]})
df_left = pd.merge(df1, df2, how = 'left')
df_right = pd.merge(df1, df2, how = 'right')
df_inner = pd.merge(df1, df2, how = 'inner')
df_outer = pd.merge(df1, df2, how = 'outer')
More details in the documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

Marcus Högenå Bohman
- 473
- 1
- 6
- 13