Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Dataframe Column to Multiple Binary Columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading