How to convert the data as following in python?
<p>I have some data in the following format in a csv file.</p>

<pre><code>   Id   Category
    1   A
    2   B
    3   C
    4   B
    5   C
    6   d
</code></pre>

<p>I'd like to convert it into the below format and save it another csv file</p>

<pre><code>Id  A   B   C   D   E
1   1   0   0   0   0
2   0   1   0   0   0
3   0   0   1   0   0
4   0   1   0   0   0
5   0   0   1   0   0
6   0   0   0   1   0
</code></pre>

<p>Use a pivot table (updated to include .csv read/write functionality):</p>

<pre><code>import pandas as pd
path = 'the path to your file'
df = pd.read_csv(path)

# your original dataframe
# Category  Id
# 0        A   1
# 1        B   2
# 2        C   3
# 3        B   4
# 4        C   5
# 5        D   6

# pivot table
df.pivot_table(index=['Id'], columns='Category', fill_value=0, aggfunc='size')

# save to file
df.to_csv('path\filename.csv') #e.g. 'C:\\Users\\you\\Documents\\filename.csv'
</code></pre>

<hr>

<p>OUTPUT:</p>

<pre><code>Category  A  B  C  D
Id                  
1         1  0  0  0
2         0  1  0  0
3         0  0  1  0
4         0  1  0  0
5         0  0  1  0
6         0  0  0  1
</code></pre>

python python-3.x pandas text-processing spyder