Skip to content

Instantly share code, notes, and snippets.

@c-l-nguyen
Last active January 17, 2021 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-l-nguyen/e03c555aefa7fc175fa810926622b25c to your computer and use it in GitHub Desktop.
Save c-l-nguyen/e03c555aefa7fc175fa810926622b25c to your computer and use it in GitHub Desktop.
Melt pandas DataFrame from wide, fat format to long, skinny format
import pandas as pd
df = pd.read_csv("Global Temperature Anomalies.csv")
print(df.columns)
# parameter values
id_vars = ['Hemisphere', 'Year']
cols_to_pivot = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'J-D', 'D-N', 'DJF', 'MAM', 'JJA',
'SON']
var_name = 'Period'
val_name = 'Temperature Diff'
# melt
output_df = pd.melt(df, id_vars=id_vars, value_vars=cols_to_pivot, var_name=var_name, value_name=val_name)
# output to csv
output_df.to_csv("output.csv", index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment