1

I am relatively new to manipulating data tables in Pandas. I have a big table like the following, say 20x bigger than this one in number of columns and rows:

import pandas as pd
df = pd.DataFrame()
df['col1']=['A','A','A','B','B','B','A','A','A','B','B','B']
df['col2']=['x','x','y','y','z','z','x','x','y','y','z','z']
df['col3']=['A1','A2','B1','B2','C1','C2','D1','D2','E1','E2','F1','F2']
df['col4']=['m','n','p','q','l','z','m','n','p','q','l','z']
df['num1']=[1,2,3,4,5,6,7,8,9,10,11,12]
df['num2']=[5,6,7,1,2,3,4,5,6,9,7,8,]
df['num3']=[11,12,13,14,15,16,17,18,19,10,11,12]
df

I want to format the table in such a way that I want to keep col1 col2, col3 as is say index them, transpose col4 elements to different rows and then stack num1, num2 and num3 columns in one column. I tried reshaping in Pandas but not having success. Getting numerous errors. How should I reshape it the way I want?

Manjit P.
  • 85
  • 1
  • 7
  • please check dupe, if still problem, let me know. – jezrael Aug 31 '18 at 07:21
  • Thanks Jezrael! df.set_index(['col1','col2','col3','col4']).stack().unstack('col4') did it. However, in my original big table I could not kept all the columns indexed that I desired. Anyway, Thanks again. – Manjit P. Aug 31 '18 at 22:18

0 Answers0