Skip to content

Instantly share code, notes, and snippets.

@derekpowell
Created January 25, 2019 22:57
Show Gist options
  • Save derekpowell/5f97dabdd0730e68380fa1a00cd34ac4 to your computer and use it in GitHub Desktop.
Save derekpowell/5f97dabdd0730e68380fa1a00cd34ac4 to your computer and use it in GitHub Desktop.
python pandas implementations of spread and gather dplyr verbs
def gather( df, key, value, cols ):
id_vars = [ col for col in df.columns if col not in cols ]
id_values = cols
var_name = key
value_name = value
return pd.melt( df, id_vars, id_values, var_name, value_name )
def spread( df, index, columns, values ):
return df.pivot(index, columns, values).reset_index(level=index).rename_axis(None,axis=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment