Pandas melt only on one variable (leaving other in long format) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Pandas melt only on one variable (leaving other in long format) (/thread-18176.html) |
Pandas melt only on one variable (leaving other in long format) - amyd - May-08-2019 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? |