Created
January 25, 2019 22:57
-
-
Save derekpowell/5f97dabdd0730e68380fa1a00cd34ac4 to your computer and use it in GitHub Desktop.
python pandas implementations of spread and gather dplyr verbs
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 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