Pandas pd.melt example
Convert data from Wide-format to Long-format
import pandas as pd
import seaborn as sns
from IPython.display import display
df = sns.load_dataset('iris')
print "Wide-format Dataframe shape: ", df.shape
display(df.head())
Wide-format Dataframe shape: (150, 5)
|
sepal_length |
sepal_width |
petal_length |
petal_width |
species |
0 |
5.1 |
3.5 |
1.4 |
0.2 |
setosa |
1 |
4.9 |
3.0 |
1.4 |
0.2 |
setosa |
2 |
4.7 |
3.2 |
1.3 |
0.2 |
setosa |
3 |
4.6 |
3.1 |
1.5 |
0.2 |
setosa |
4 |
5.0 |
3.6 |
1.4 |
0.2 |
setosa |
df_long = pd.melt(df, id_vars="species")
print "Long-format Dataframe shape: ", df_long.shape
display(df_long.head())
Long-format Dataframe shape: (600, 3)
|
species |
variable |
value |
0 |
setosa |
sepal_length |
5.1 |
1 |
setosa |
sepal_length |
4.9 |
2 |
setosa |
sepal_length |
4.7 |
3 |
setosa |
sepal_length |
4.6 |
4 |
setosa |
sepal_length |
5.0 |
Change Variable Name
df_long = pd.melt(df, id_vars="species", var_name="measurement")
print "Long-format Dataframe shape: ", df_long.shape
display(df_long.head())
Long-format Dataframe shape: (600, 3)
|
species |
measurement |
value |
0 |
setosa |
sepal_length |
5.1 |
1 |
setosa |
sepal_length |
4.9 |
2 |
setosa |
sepal_length |
4.7 |
3 |
setosa |
sepal_length |
4.6 |
4 |
setosa |
sepal_length |
5.0 |
Reference