Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearrange dataframe to a table, the opposite of "melt" [duplicate]

I have huge dataframe like this:

SN = c(1:100, 1:100, 1:100, 1:100)   class = c(rep("A1", 100), rep("B2", 100), rep("C3", 100), rep("D4", 100)) # total 6000 levels  myvar = rnorm(400) mydf = data.frame(SN, class, myvar)  

I want to "unmelt" to a table with each level as single column and myvar in filled:

SN          A1            B2          C3         D4       .............and so on for all 6000  

How can I achieve this, I know it is simple question, but I could not figure out.

like image 838
jon Avatar asked Oct 19 '11 20:10

jon


People also ask

What is the reverse of melt in pandas?

We can also do the reverse of the melt operation which is also called as Pivoting. In Pivoting or Reverse Melting, we convert a column with multiple values into several columns of their own. The pivot() method on the dataframe takes two main arguments index and columns .

What is the opposite of melt in R?

5. 4. In package reshape2 the opposite of melt is cast.

Why do pandas melt?

Pandas melt() function is used to change the DataFrame format from wide to long. It's used to create a specific format of the DataFrame object where one or more columns work as identifiers. All the remaining columns are treated as values and unpivoted to the row axis and only two columns - variable and value.

What is melting in Python?

melt() function is useful to message a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.


2 Answers

> dcast(mydf, SN ~ class)    SN         A1         B2          C3          D4 1  1  0.1461258  0.8325014  0.33562088 -0.07294576 2  2  0.5964182  0.4593710 -0.23652803 -1.52539568 3  3  2.0247742 -1.1235963  1.79875447 -1.87462227 4  4  0.8184004  1.3486721  0.76076486 -1.18311991 5  5 -0.6577212  0.3666741 -0.06057506  1.38825487 6  6  0.1590443  0.2043661  0.08161778  0.10421797 ... 
like image 157
John Colby Avatar answered Sep 28 '22 02:09

John Colby


molten = melt( mydf , id.vars = c( "SN" , "class" ) , measure.vars = "myvar" ) casted = dcast( molten , SN~class ) 
like image 21
SFun28 Avatar answered Sep 28 '22 03:09

SFun28