简体   繁体   中英

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.

Data

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


        

Desired

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

Doing

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

No need box

df1 = pd.crosstab(df["location"], df["type"])
Out[271]: 
type      hello  hey  hi
location                
ca            1    0   1
ny            3    2   0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM