Skip to content

Instantly share code, notes, and snippets.

@kstreepy
Created May 30, 2019 12:02
Show Gist options
  • Save kstreepy/ab183d444159fe4d100a43a5dd094305 to your computer and use it in GitHub Desktop.
Save kstreepy/ab183d444159fe4d100a43a5dd094305 to your computer and use it in GitHub Desktop.
Given a wide dataframe, use melt to transform from wide to long. Declare the ID Columns and establish value columns as all remaining columns in dataframe.
import pandas as pd
def quick_melt(wide_df):
'''
Take wide dataframe and melt to long. Declare ID Columns (id_cols)
and then establish all remaining columns as value columns
'''
id_cols = {'A', 'B', 'C'}
value_cols = set(wide_df.columns) - id_cols
long_df = pd.melt(wide_df,
id_vars= list(id_cols),
value_vars= list(value_cols),
var_name='Variable',
value_name='Value')
return long_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment