简体   繁体   中英

Failed to count occurrence of values in dataFrame based on few columns with groupby

I have pandas dataframe:

id   colA  colB  colC  
194    1    0     1
194    1    1     0
194    2    1     3
195    1    1     2
195    0    1     0
197    1    1     2

i would to calculate occurrence of each value group by id. in my case, expected result is:

id   countOfValue0    countOfValue1   countOfValue2   countOfValue3
194       2                 3                1              1
195       1                 2                1              0
197       0                 1                1              0

if value appeared in same row - distinct value by row (this is why i have for id=194, value1 = 3) i thought to separate the data to 3 data frames using group by id-colA, id-colB, id-colC something like = df.groupby('id', 'colaA') but i can't find an proper way to calculate those dataframe values based on id. probably there is more efficient way for doing this

Try:

res=df.set_index("id", append=True).stack()\
.reset_index(level=0).reset_index(level=1,drop=True)\
.drop_duplicates().assign(_dummy=1)\
.rename(columns={0: "countOfValue"})\
.pivot_table(index="id", columns="countOfValue", values="_dummy", aggfunc="sum")\
.fillna(0).astype(int)

res=res.add_prefix("countOfValue")
del res.columns.name

Outputs:

     countOfValue0  ...  countOfValue3
id                  ...
194              2  ...              1
195              1  ...              0
197              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