0

I have an excel sheet like this:

https://i.sstatic.net/F1807.png

I would like to output the data into an excel file like this:

https://i.sstatic.net/K8tWY.png

Basically, for the common elements in column 2,3,4, I want to contacenate the values in the 5th column.

Please suggest, how could I do this ?

1 Answer 1

1

The easiest way to approach an issue like this is exporting the spreadsheet to CSV first, in order to help ensure that it imports correctly into Python.

Using a defaultdict, you can create a dictionary that has unique keys and then iterate through lines adding the final column's values to a list.

Finally you can write it back out to a CSV format:

from collections import defaultdict

results = defaultdict(list)

with open("in_file.csv") as f:
    header = f.readline()
    for line in f:
        cols = line.split(",")
        key = ",".join(cols[0:4])
        results[key].append(cols[4])

with open("out_file.csv", "w") as f:
    f.write(header)
    for k, v in results.iteritems():
        line = '{},"{}",\n'.format(k, ", ".join(v))
        f.write(line)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.