Group and take count by expanding values in column Pandas


I wish to groupby and then create column headers with the values in a specific column and list their counts.


location    box     type    
ny          box11   hey 
ny          box11   hey 
ny          box13   hello   
ny          box13   hello   
ny          box13   hello   
ca          box5    hi  
ca          box8    hello



location    hey hello   hi
ny          2   3       0
ca          0   1       1


using crosstab as SO member assisted w this script.

first group, then crosstab

df1 = df.groupby(["location", "box"]).agg()

df2 = pd.crosstab([df["location"], df["box"]], df["type"])

Any suggestion is appreciated- still researching

Asked By: Lynn



No need box

df1 = pd.crosstab(df["location"], df["type"])
type      hello  hey  hi
ca            1    0   1
ny            3    2   0
Answered By: BENY
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.