Pandas: get a new column for each unique row

Viewed 23

I have a Pandas DF in the following format:

df:

Name Feature Count
A aa 2
A bb 1
B bb 3
B cc 1
C dd 2

I would like to transform the DF into something like this:

Name Feature aa Feature bb Feature cc Feature dd
A 2 1 0 0
B 0 3 1 0
C 0 0 0 2

(cells now are counts related to Names and features).

How can I get this result? Please, I need your help.

1 Answers

Try .pivot():

print(
    df.pivot(index="Name", columns="Feature", values="Count")
    .fillna(0)
    .add_prefix("Feature ")
    .astype(int)
    .reset_index()
)

Prints:

Feature Name  Feature aa  Feature bb  Feature cc  Feature dd
0          A           2           1           0           0
1          B           0           3           1           0
2          C           0           0           0           2
Related