Home » excel » Reformatting Excel spreadsheet in Python

Reformatting Excel spreadsheet in Python

Posted by: admin April 23, 2020 Leave a comment


enter image description here

Hi everyone, I received data in a excel (xls) spreadsheet that is formatted in the first table, illustrated above.

I am attempting to rearrange this data into the format, in the table, just below. Any help would be greatly appreciated.

Thanks much.

How to&Answers:

First, save it to a .csv file

import csv

curr = []
with open('file.csv') as infile, open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout)
    for area, pop10, pop20, pop50 in csv.reader(infile):
        if curr and curr[0] != area:
            curr = [area, pop10, pop20, pop50]

        if pop10: curr[1] = pop10
        if pop20: curr[2] = pop20
        if pop50: curr[3] = pop50


You can do this pretty succinctly using Pandas:

import pandas as pd
dataframe = pd.read_excel("in.xlsx")
merged = dataframe.groupby("AREA").sum()


so, if the csv has 11 columns where ‘AREA’ is the second column, would the code be:

def CompressRow(in_csv,out_file):
    curr = []
    with open(in_csv) as infile, open(out_file, 'w') as fout:
        outfile = csv.writer(fout)
        for a,b,c,d,e,f,g,h,i,j,k in csv.reader(infile):
            if curr and curr[1] != b:
                curr = [a,b,c,d,e,f,g,h,i,j,k]

            if a: curr[0] = a
            if c: curr[2] = c
            if d: curr[3] = d
            if e: curr[4] = e
            if f: curr[5] =f
            if g: curr[6]=g
            if h: curr[7]=h
            if i: curr[8]=i
            if j: curr[9]=j
            if k: curr[10]=k

#execute CompressRow(in_csv,out_file)

I tried executing it and it gives me

if a: curr[0]=a

 IndexError: list assignment index out of range