Python Forum
Pandas melt only on one variable (leaving other in long format)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pandas melt only on one variable (leaving other in long format)
#1
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pandas keep existing format of Excel AlphaInc 2 2,090 Jan-11-2024, 03:44 AM
Last Post: plonkarchivist
  Help to control pandas.melt function vanphuht91 0 810 Jun-17-2023, 08:41 AM
Last Post: vanphuht91
  xlswriter(pandas) and conditional format paul18fr 1 1,304 Aug-28-2022, 07:56 AM
Last Post: paul18fr
  loading a csv file into python from pandas. Variable is not recognized vijjumodi 2 3,041 Apr-19-2019, 04:09 AM
Last Post: kus
  ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long long' MaJeFi 2 13,013 Mar-20-2019, 06:00 AM
Last Post: MaJeFi
  Python pandas remove default format in excel indra 0 2,850 Feb-06-2019, 04:48 AM
Last Post: indra
  Read CSV data into Pandas DataSet From Variable? Oliver 7 14,475 Jul-05-2018, 03:29 AM
Last Post: answerquest
  Melt or Slice Grin 0 2,282 Jun-24-2018, 06:02 PM
Last Post: Grin

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020