Python Forum

Full Version: Pandas melt only on one variable (leaving other in long format)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have the following data:

import pandas as pd
import numpy as np
 
data = [
    ['Dog', 5, 0.25,5.5,0.23],
    ['Cat', 3, 0.15,2.8,0.17],]
 
df = pd.DataFrame(columns=["Type", "Weight_Apr_18", "Factor_Apr_18", "Weight_May_18", "Factor_May_18",], data=data)
But for all the months in 2018.

I want to reshape my data from wide to long to get the following output:

import pandas as pd
import numpy as np
 
data = [
    ['Dog', 5, 0.25,'Apr_18'],
    ['Dog', 5.5, 0.23,'May_18'],    
    ['Cat', 3, 0.15,'Apr_18'],
    ['Cat',2.8,0.17,'May_18']]
 
df2 = pd.DataFrame(columns=["Type", "Weight", "Factor","Period"], data=data)
So I try to melt my data as follows:

df = df.melt(id_vars=['Type'])
However, that gives me a column called variable which has both the weight and the factor as well as the date. Is there a way getting my desired output from melt?