Skip to content

Instantly share code, notes, and snippets.

@pjankiewicz
Last active January 1, 2016 03:48
Show Gist options
  • Save pjankiewicz/8087446 to your computer and use it in GitHub Desktop.
Save pjankiewicz/8087446 to your computer and use it in GitHub Desktop.
python pandas left join function
def left_join(df1, df2, key, cols, lsuffix="", rsuffix="", default_value=None):
if type(key) != list:
key_left, key_right = key, key
else:
key_left, key_right = key[0], key[1]
if type(cols) != list:
cols = [cols,]
ind = pd.match(df1[key], df2[key])
ind_left = np.where(ind>=0)[0]
ind_right = ind[ind>=0]
for col in cols:
alias = lsuffix + col + rsuffix
df1[alias] = default_value
df1[alias][ind_left] = df2.ix[ind_right,col]
return df1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment