Head of Digital Marketing @Bronco. Lover of Python and Data.

Dealing With Merged Cells With Python

Here's a quick script for dealing with merged CSV cells. Basically, if you need to unmerge a bunch of cells and duplicate what the value was into the split cells, here's an easy was to do it with Python.

I've just had to do this over a ducument with almost 2 thousand rows, so I knocked this together and though I'd share it.


# -*- coding: utf-8-*-
import csv

def get_index(lis):
	''' returns the index values 
	for empty strings.
	'''
    results = []
    for count, item in enumerate(lis):
        if item == '':
            results.append(count)
    return results      

with open('input.csv') as f:
	data = csv.reader(f)
	last_row = ''
	for row in data:
		if '' not in row:
			last_row = row
		else:
			for i in get_index(row):
				row[i] = last_row[i]

		with open('output.csv', 'a') as out:
			w = csv.writer(out)
			w.writerow(row)


Give Your Inbox Some Love


What You'll get?
  • Posts like this delivered straight to your inbox!
  • Nothing else.
Comment Policy

Any code snippets more than a line or 2, please include as a link to a gist

comments powered by Disqus