Используйте groupby
с size
и измените на unstack
, последний add_prefix
:
df = df.groupby(['term','score']).size().unstack(fill_value=0).add_prefix('score ')
Или используйте crosstab
:
df = pd.crosstab(df['term'],df['score']).add_prefix('score ')
Или pivot_table
:
df = (df.pivot_table(index='term',columns='score', aggfunc='size', fill_value=0)
.add_prefix('score '))
print (df)
score score 0 score 1 score 2 score 3
term
anything 0 1 0 0
something 0 1 1 0
that 0 1 1 0
the other 0 0 1 1
this 2 0 0 0