Issue
Suppose we have the following df
:
import pandas as pd
data = {"Team": ["Red Sox", "Red Sox", "Red Sox", "Red Sox", "Red Sox", "Red Sox", "Yankees", "Yankees", "Yankees", "Yankees", "Yankees", "Yankees"],
"Pos": ["Pitcher", "Pitcher", "Pitcher", "Not Pitcher", "Not Pitcher", "Not Pitcher", "Pitcher", "Pitcher", "Pitcher", "Not Pitcher", "Not Pitcher", "Not Pitcher"],
"Age": [24, 28, 40, 22, 29, 33, 31, 26, 21, 36, 25, 31]}
df = pd.DataFrame(data)
When I groupby
two keys Team and Pos
what I get is:
print(df.groupby(['Team','Pos'])['Age'].count())
Team Pos Age
0 Red Sox Not Pitcher 3
1 Red Sox Pitcher 3
2 Yankees Not Pitcher 3
3 Yankees Pitcher 3
I would like to have levels of Pos
index into columns as such:
Team Not_Pitcher Pitcher
Red Sox 3 3
Yankees 3 3
Solution
Try pd.crosstab
pd.crosstab(df.Team,df.Pos)
Pos Not Pitcher Pitcher
Team
Red Sox 3 3
Yankees 3 3
Answered By - BENY
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.