user9101682
user9101682

Reputation: 1

Adding new column to CSV in Python

I would like to add a new column to my CSV in Python. I understand that in Python I will have to run the CSV and rewrite a new one as an output to add a column.

I want to run though each UserID and assign a UniqueID to it.

This is my input:

UserID,name
a,alice
a,alice
b,ben
c,calvin
c,calvin
c,calvin

This is my desired output:

UniqueID,UserID,name
1,a,alice
1,a,alice
2,b,ben
3,c,calvin
3,c,calvin
3,c,calvin

I am new to Python and was wondering if anyone can show me how this can be done. Thanks.

Here is my code so far: 
import csv
import operator

temp_index = 0

with open("./coordinates.csv") as all_coordinates_csv:
    coordinate_reader = csv.reader(all_coordinates_csv, delimiter=",")

    sort = sorted(coordinate_reader,key=operator.itemgetter(0))

with open("./sorteduserid.csv","wb") as sorteduser_csv:
    csv_writer = csv.writer(sorteduser_csv,delimiter=",")
    csv_writer.writerows(sort)

Upvotes: 0

Views: 737

Answers (2)

atru
atru

Reputation: 4744

This solution is based on your own attempt:

import csv
import operator
from itertools import groupby

with open("./coordinates.csv") as all_coordinates_csv:
    coordinate_reader = csv.reader(all_coordinates_csv, delimiter=",")

    sort = sorted(coordinate_reader,key=operator.itemgetter(0))

grouped = []
for key, group in groupby(sort, lambda x: x[0]):
    grouped.append(list(group))

data_out = [];
data_out.append(['Unique_ID', (grouped[0])[0][0], (grouped[0])[0][1]])

user_id = 1
for group in grouped[1:]:
    for user in group:
        data_out.append([user_id,user[0],user[1]])
    user_id += 1

with open("./sorteduserid.csv","wb") as sorteduser_csv:
    csv_writer = csv.writer(sorteduser_csv,delimiter=",")
    csv_writer.writerows(data_out)

After you sort your input the program uses groupby to group the values by UserID in sort. It then uses those grouped values in the loops to assign a unique ID to each UserID. Before the loops, it extends the header with User_ID entry.

Upvotes: 0

ericping
ericping

Reputation: 45

Take a try with my code:

import csv
import uuid

is_first = True
with open('test.csv', newline='') as input_file:  
    with open('output.csv', 'w', newline='') as output_file:
        writer = csv.writer(output_file)
        reader = csv.reader(input_file)
        for row in reader:
            if is_first:
                row.insert(0, 'UniqueID')
                is_first = False
            else:
                row.insert(0, str(uuid.uuid4()))

            writer.writerow(row)

Upvotes: 3

Related Questions