Created
December 3, 2017 15:20
-
-
Save milo0/e1dfe251761f5e1570a5c57335f396a5 to your computer and use it in GitHub Desktop.
Merge two pandas DataFrames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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