-
-
Save lzhbrian/c2a7473ce5d11ed5704ee1764f4d53aa to your computer and use it in GitHub Desktop.
Turn certain columns to key-value rows ( and the reverse )
This file contains hidden or 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
""" | |
Turn this | |
location name Jan-2010 Feb-2010 March-2010 | |
A "test" 12 20 30 | |
B "foo" 18 20 25 | |
into this | |
location name Date Value | |
A "test" Jan-2010 12 | |
A "test" Feb-2010 20 | |
A "test" March-2010 30 | |
B "foo" Jan-2010 18 | |
B "foo" Feb-2010 20 | |
B "foo" March-2010 25 | |
Reference: https://stackoverflow.com/questions/28654047/pandas-convert-some-columns-into-rows | |
""" | |
########## Using pandas.melt | |
import pandas as pd | |
df = pd.DataFrame({"location": ["A", "B"], "name": ["test", "foo"], | |
"Jan-2010": [12, 18], "Feb-2010": [20, 20], "Mar-2010": [30, 25]}) | |
df2 = pd.melt(df, id_vars=["location", "name"], var_name="Date", value_name="Value") | |
df2 = df2.sort_values(["location", "name"]) | |
############## | |
# TODO: how to do the reverse process |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment