Last active
January 17, 2021 17:16
-
-
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
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
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