2

I have the nexy code in Python

Id=np.arange(1,16)

l=np.arange(1,101).tolist()

Ing=random.choices(l,k=15)

base2= pd.DataFrame({'Id':Id,'Ingreso':Ing,})

base2=base2.set_index('Id')

base2['Grupo'] = pd.cut(base2['Ingreso'], bins=[0,30,50,70,100],labels=[1,2,3,4], include_lowest=True)

grouped = base2.groupby(['Ingreso', 'Grupo'], as_index=False)

s=np.arange(0,2).tolist()

base2['Sexo']= random.choices(s,k=15)

With this dataframe I want to do a Crosstable

pd.crosstab(base2.Grupo,base2.Sexo)

And this is my output

Sexo   0  1
Grupo      
1      1  2
2      2  2
3      0  3
4      3  2

But I want something Like this

Sexo Men Women 
Grupo      
1      1  2
2      2  2
3      0  3
4      3  2

It is posible in Python ?

1
  • try pd.crosstab(base2.Grupo,base2.Sexo).set_axis(['Men','Women'],axis='columns') Commented Mar 22, 2020 at 21:28

1 Answer 1

2

Use Series.map before.

pd.crosstab(base2.Grupo, base2.Sexo.map({0 : 'Men', 1 : 'Women'}))

or DataFrame.rename after.

pd.crosstab(base2.Grupo, base2.Sexo).rename(columns={0 : 'Men', 1 : 'Women'})

Output

Sexo Men Women 
Grupo      
1      1  2
2      2  2
3      0  3
4      3  2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.