Saving Excel rows into lists in Python

Question:

I basically want to save (for each row) the first 5 cells as floats to a list (say list1) then the sixth cell to another list (list2), then save both these to a list (list3). I want to do this for each rows and save each list3 for each row to one final list (sorry I know I said list alot),

So for example, for the data in the photo (labelled excel data below), I want to save it as:

final_list = [[[1.1,1.2,1.3,1.4,1.5],[1.6]], [[2.1,2.2,2.3,2.4,2.5],[2.6]],[[3.1,3.2,3.3,3.4,3.5],[3.6]]]

if that makes sense? What would be the easiest way to do this, I am a beginner at python.

excel data

Asked By: Elee

||

Answers:

Most common way of working with tables in Python is Pandas. If you just want plain lists this answer that uses openpyxl might tell you what you need.

For your case would be something like this:

from openpyxl import load_workbook

path_to_wb = ...
my_wb = load_workbook(path_to_wb)

first_sheet = my_wb.worksheets[0]

whole_list = []
# Iter all the rows
for i in range(5):
    # Get first columns
    first_columns = [first_sheet.cell(row = i + 1, column = j + 1).value
                     for j in range(5)]
    
    # Create a list with one single element, last column
    last_element = [first_sheet.cell(row = i + 1, column = 6).value]

    # Add a list with two elements
    whole_list.append([first_columns, last_element])

If you would prefer a list comprehension, you can get rid of the loop:

whole_list = [[[first_sheet.cell(row = i + 1, column = j + 1).value for j in range(5)],
               [first_sheet.cell(row = i + 1, column = 6).value]]
              for i in range(5)]

Let me point out that this is what you asked for, but it is not the usual methodology for working with tables in Python.

Answered By: Jorge Luis

I think this is what you want:

Assuming data is a 2D list where each row contains 6 elements

data = [[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
        [7.0, 8.0, 9.0, 10.0, 11.0, 12.0],
        [13.0, 14.0, 15.0, 16.0, 17.0, 18.0]]

Initialize empty list to hold final results

final_list = []

for row in data:
    # Extract the first 5 elements of the row and convert to floats
    list1 = list(map(float, row[:5]))
    
    # Extract the 6th element of the row and append to list2
    list2 = [row[5]]
    
    # Combine list1 and list2 into a single list
    list3 = list1 + list2  # might be [list1, list2]
    
    # Append list3 to the final list
    final_list.append(list3)

Answered By: Sean
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.