'Single column to multiple columns with columns as heading and fill with binary values
Given column in the csv file
labels    
['N']    
['C']   
['D']   
['A']   
['D','C']   
['H']   
['D','G']
['M']       
['O']   
I want the labels as separate column headers and fill them with binary values. and there are total 8 labels which is N,D,G,C,A,H,M,O .The code I have written is as shown below contains problem that each label even if it is in this form ['D','G'] is considered as separate column
Code snippet given below:
df = (df.pivot(index="ID",columns="labels", values='target')
            .rename_axis(None, axis=1)
            .reset_index())
Expected Output:
|N| D| G| C| A| H| M| O|
|1 |0 |0 |0 |0 |0 |0| 0|
|0| 0| 1| 0| 0| 0| 0|0|
These output are for the first 2 rows given above Also add these new columns in the same csv file . Thanks in advance
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|
