1

What is an opposite operation to pd.DataFrame.melt when no index is used? In example below I need to get the df from df2.

>>>df = pd.DataFrame({"a" : [1,2,3], "b" :[4,5,6], "c":[10,11,12]})
>>>print(df)

   a  b   c
0  1  4  10
1  2  5  11
2  3  6  12

>>>df2 = df.melt()
>>>print(df2)

  variable  value
0        a      1
1        a      2
2        a      3
3        b      4
4        b      5
5        b      6
6        c     10
7        c     11
8        c     12
Pepacz
  • 881
  • 3
  • 9
  • 24
  • That operation is often called "pivoting." Check out the documentation for "dataframe.pivot()" and "dataframe.pivot_table()". There are many good answers about this on SO already. Here's a fairly comprehensive one https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe – HarlandMason Feb 07 '18 at 18:43

1 Answers1

2

It is pivot or crosstab or pivot_table or stack unstack, but before doing that you need cumcount get the index

#d=df.melt()
d.assign(index=d.groupby('variable').value.cumcount()).pivot('index','variable','value')
Out[1443]: 
variable  a  b   c
index             
0         1  4  10
1         2  5  11
2         3  6  12
BENY
  • 317,841
  • 20
  • 164
  • 234
  • I was hoping for something like `R`'s `dcast(df2, .~variable, value.var="value")`, but fair enough (-; – Pepacz Feb 07 '18 at 19:14
  • @Pepacz hah, sometime R is more easy with spread , if you are interesting , you can check tidyverse – BENY Feb 07 '18 at 19:18