Pandas Dataframe Column to Multiple Binary Columns [duplicate]

I have a DataFrame like

    Instance Class IsApplicable
0   A           1   True
1   A           2   True
2   A           3   False
3   B           1   False
4   B           2   False
5   B           3   False
6   C           1   True
7   C           2   True
8   C           3   True

and want to turn it into

    Instance    1     2     3
0   A           True  True  False
1   B           False False False
2   C           True  True  True 

I solved it with a for loop like

for i in unique_instances:
    df_curr = df.where(df['Instance'] == i).dropna()
    curr_row = dict(zip(df_curr.Class, df_curr.IsApplicable))
    curr_row['Instance'] = i
    df_out.append(curr_row,ignore_index=True)

but this seems neither efficient nor elegant.


You can use pivot:

out = df.pivot('Instance','Class','IsApplicable').reset_index().rename_axis(columns=[None])

Output:

  Instance      1      2      3
0        A   True   True  False
1        B  False  False  False
2        C   True   True   True