wide to long

Last Updated on April 12, 2023 by mishou

The typos are corrected.

I.What do you learn?

Let me show you how to convert a data frame from wide to long format. You have to use long formats when you create charts with Plotly and Seaborn.

II.Scripts

1.Using melt

import pandas as pd

# Create example DataFrame in wide format
dic = {'ID': [1, 2, 3],
       'Gender': ['Male', 'Female', 'Female'],
       'Age_2010': [25, 30, 35],
       'Age_2015': [30, 35, 40],
       'Age_2020': [35, 40, 45]}
df = pd.DataFrame(dic)
# Convert data from wide to long format
id_vars = ['ID', 'Gender']
value_vars = ['Age_2010', 'Age_2015', 'Age_2020']
df_long = pd.melt(df,
                  id_vars=id_vars,
                  value_vars=value_vars,
                  var_name='Year',
                  value_name='Age')

You can see the code on Google Colaboratory:

https://colab.research.google.com/drive/1BJjuWsuoJAaSa_CZk5Y9F0rD0hQBv0ou?usp=sharing

2.Using wide_to_long

You can easily take care of the prefix in the column names with eide_to_long.

pandas.wide_to_long(df, stubnames, i, j, sep='', suffix='\d+')
The first four parameters must be provied.

By mishou

Leave a Reply

Your email address will not be published. Required fields are marked *