Calculate and add column in python

3.5k Views Asked by At

I think I have a fairly simple question for a python expert. With a lot of struggling I put together underneath code. I am opening an excel file, transforming it to a list of lists and adding a column to this list of lists. Now I want to rename and recalculate the rows of this added column. How do I script that I always take the last column of a list of lists, even though the number of columns could differ.

import xlrd
file_location = "path"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
data = [x + [0] for x in data]
2

There are 2 best solutions below

0
On BEST ANSWER

I found a more easy and more flexible way of adjusting the values in the last column.

counter = 0
for list in data:
    counter = counter + 1
    if counter == 1:
        value = 'Vrspng'
    else:
        value = counter
    list.append(value)
2
On

If you have a function called calculate_value that takes a row and returns the value for that row, you could do it like this:

def calculate_value(row):
    # calculate it...
    return value

def add_calculated_column(rows, func):
    result_rows = []
    for row in rows:
        # create a new row to avoid changing the old data
        new_row = row + [func(row)]
        result_rows.append(new_row)
    return result_rows

data_with_column = add_calculated_column(data, calculate_value)