Skip to content

Instantly share code, notes, and snippets.

@milo0
Created December 3, 2017 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milo0/e1dfe251761f5e1570a5c57335f396a5 to your computer and use it in GitHub Desktop.
Save milo0/e1dfe251761f5e1570a5c57335f396a5 to your computer and use it in GitHub Desktop.
Merge two pandas DataFrames
def merge_dfs(df1, df2):
"""Merge two DataFrames. Common columns among the dfs are reduced to one."""
res = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
cols = sorted(res.columns)
pairs = []
for col1, col2 in zip(cols[:-1], cols[1:]):
if col1.endswith('_x') and col2.endswith('_y'):
pairs.append((col1, col2))
for col1, col2 in pairs:
res[col1[:-2]] = res[col1].combine_first(res[col2])
res = res.drop([col1, col2], axis=1)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment