Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent 'spread' and 'gather' in R/tidyverse in python/pandas?

Tags:

python

pandas

for example. Data A:

y female male
1 2 3
4 5 6

I want to 'gather' it to this:

y gender value
1 female 2
1 male 3
4 female 5
4 male 6

It's easy in R. What about python pandas?

like image 380
Bin Avatar asked Dec 13 '22 14:12

Bin


1 Answers

You should try melt , in the given data , the opposite(spread version is called cast), these melt and cast functions are very similar to R's reshape2:

import pandas as pd    
pd.melt(dt, id_vars="y")

Where dt is your input table

Output:

#y  variable      value
#1  female          2
#4  female          5
#1  male            3
#4  male            6
like image 124
PKumar Avatar answered Jan 25 '23 22:01

PKumar