简体   繁体   中英

Calculate the number of occurrences of a column value value *per* unique id

I want to calculate the number of occurrences of a columnvalue per unique id and store them in a new panda Dataframe:

Dataframe (simplified):

在此处输入图片说明

Desired output:

在此处输入图片说明

Keywords are +1.000s and not known. Have tried by creating lists and zipping them, but not really working.

尝试使用crosstab

pd.crosstab(df['unique id'],df['keyword'])

Use groupby apply with Counter , untack and fillna :

from collections import Counter
df.groupby('unique id')['keyword'].apply(Counter).to_frame().unstack(1).fillna(0)

          keyword            
             auto fish mobile
unique id                    
1a            2.0  1.0    1.0
2a            1.0  2.0    1.0
3a            0.0  1.0    0.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