0

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
  • What do you mean by adding a column to a list of lists? Do you mean you add an element to the inner list? Commented Dec 22, 2014 at 9:40
  • I got it from here: stackoverflow.com/questions/2002415/… He calls it adding a column. Not sure if that is exactly what I do but it appears to be what I want. Commented Dec 22, 2014 at 9:41

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This looks like what I want. Thank you. Going to test it now.
Ok. This has helped a lot already. I am capable of recalculating a value in the last column. However, I want my first row to have a different value than the second row of the column. The first row being integer and the second row being a calculated value.
0

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)

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.