Q: Creating a nxm matrix from a csv dataset I'm a new Python user so forgive me if the question seems stupid.
I have a dataset in .csv format and I need to create a binary matrix from it. It looks like that: 
A (events), B (group1), C (group2), D (group3) 
1           isis        al qaeda
2           al qaeda
3           boko h. 
4           boko h.     al shabaab  isis

and I want to create a binary matrix (nxm) where col A = n, and m is the list of the unique elements contained in B, C, D. So, my output should look like:      
A (events), isis, al qaeda, boko h., al shabaab 
1            1      1        0        0
2            0      1        0        0  
3            0      0        1        0      
4            1      0        1        1

The elements inside the matrix are [0;1]. 0 when in the first dataset, for the event A(i) that particular group was not recorded, 1 otherwise.
I have no idea how to do it... Can you help me? Thanks

A: You first need to read all the data in and determine the set of unique entries. With this you can create a sorted list of columns to use. Next write each row of the data to your output CSV file using a list comprehension to decide if a given column entry is present:
import csv

with open('input.csv', 'rb') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)
    data = list(csv_input)
    unique = sorted(set(x for row in data for x in row[1:]))

with open('output.csv', 'wb') as f_output:    
    csv_output = csv.writer(f_output)
    csv_output.writerow([header[0]] + unique)

    for row in data:
        csv_output.writerow([row[0]] + [1 if e in row[1:] else 0 for index, e in enumerate(unique)])

This assumes you are using Python 2.x and that your input CSV data is comma separated. For Python 3.x, you would need to change two lines:
with open('input.csv', 'r', newline='') as f_input:
with open('output.csv', 'w', newline='') as f_output:

