Pandas long to wide, multiple columns

Viewed 263

I am in the process of learning Python.

I already know R but I will admit I am struggling to learn Python.

Let's say I have a Pandas data frame (named: df_original) that has 50 columns.

Column0 - Column47 are a mix of character, numeric, dates, etc.

Now let's say that Column48 is a character column with three (3) groups.

The groups are "Company1", "Company2", and "Company3".

The last column, Column49 is a numeric.

In R, if I wanted to reshape the data frame from long to wide, the code would be...

df_reshaped <- reshape(df_original,
v.names = "Column49",
idvar = c("Column1", "Column2", ... "Column46", "Column47"),
timevar = "Column48",
direction = "wide")

I have spent hours searching online but I just can't seem to find the code/example I am looking for.

Thanks in advance for the help.

Regards.

Dan

1 Answers

In pandas we have pivot

out = df.pivot(index=["Column1", "Column2", ... "Column46", "Column47"],values=['Column49'],columns=['Column48'] )
Related