Stack dataframe columns into rows - 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: Stack dataframe columns into rows (/thread-4680.html) |
Stack dataframe columns into rows - klllmmm - Sep-03-2017 I have a large dataframe loaded from a CSV file. I want to stack the columns related to each product into rows. This is a sample of the dataframe, real dataset i have many coumns for more product quantities & Product Vales import pandas as pd import numpy as np csvData = pd.DataFrame(data = {'Date':['01-09-17','01-09-17','02-09-17'], 'CustomerCode':['C100','C200','C100'], 'CustomerName':['CustomerA','CustomerB','CustomerA'], 'ProductA_Qty':[50,70,60], 'ProductA_Value':[1000,1400,1200], 'ProductB_Qty':[40,np.nan,20], 'ProductB_Value':[800,np.nan,400] },columns=['Date', 'CustomerCode', 'CustomerName','ProductA_Qty','ProductA_Value','ProductB_Qty','ProductB_Value'])I'm expecting an output similar to below table Code i tried is as follows, However the result is not as i expected;new = pd.melt(csvData, id_vars=['Date','CustomerCode','CustomerName'], var_name='Product', value_name='Values')Result i'm getting from above code is; Highly appreciate if someone can help me to achive the expected result.Thanks for your time & efforts. |