Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Pandas melt only on one variable (leaving other in long format)

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'],
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?

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  loading a csv file into python from pandas. Variable is not recognized vijjumodi 2 639 Apr-19-2019, 04:09 AM
Last Post: kus
  ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long long' MaJeFi 2 3,466 Mar-20-2019, 06:00 AM
Last Post: MaJeFi
  Python pandas remove default format in excel indra 0 521 Feb-06-2019, 04:48 AM
Last Post: indra
  Read CSV data into Pandas DataSet From Variable? Oliver 7 6,636 Jul-05-2018, 03:29 AM
Last Post: answerquest
  Melt or Slice Grin 0 660 Jun-24-2018, 06:02 PM
Last Post: Grin

Forum Jump:

Users browsing this thread: 1 Guest(s)