Home > Net >  Merge rows in a CSV to a column
Merge rows in a CSV to a column

Time:01-01

I am new in python, I have one CSV file, it has more than 1000 rows, I want to merge particular rows and move those rows to another column, can any one help?

This is the source csv file I have:

Source CVS file

I want to move emails under members column with comma separator, like this image:

Output

CodePudding user response:

To read csv files in Python, you can use the csv module. This code does the merging you're looking for.

import csv

output = []  # this will store a list of new rows

with open('test.csv') as f:
    reader = csv.reader(f)
    
    # read the first line of the input as the headers
    header = next(reader)
    output.append(header)
    
    # we will build up groups and their emails
    emails = []
    group = []
    for row in reader:
        if row[1]:   # "UserGroup" is given
            if group:
                group[-1] = ','.join(emails)
            group = row
            output.append(group)
            emails = []
        else:  # it isn't, assume this is an email
            emails.append(row[0])

    group[-1] = ','.join(emails)

# now write a new file
with open('new.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(output)

CodePudding user response:

As meny mentioned, this csv file is unproperly structured, but when you deal with that, i recommend you look at a guide like this from Realpython: https://realpython.com/python-csv/

The reason i didn't just give you a code answer is because that is considered spoon-feeding, we will happily help out if you atleast show us what code you tried and what that does, but you can't expect to just receive a block of working code.

  • Related