Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract excel columns into python array

I want to extract excel columns (NOT rows) into python arrays of array. It has to be arrays, not dictionaries.

The excel file looks like this:

     A    B    C
1   123  534  576
2   456  745  345
3   234  765  285

I want to bring this into python in the following format:

[[123,534,576],[456,745,345],[234,765,285]]

How would I do this? Thank you

like image 997
user1681664 Avatar asked Mar 20 '14 18:03

user1681664


People also ask

How extract specific data from Excel to Python?

Method 2: Reading an excel file using Python using openpyxlThe load_workbook() function opens the Books. xlsx file for reading. This file is passed as an argument to this function. The object of the dataframe.


2 Answers

Here's a yet simpler approach:

import xlrd
book = xlrd.open_workbook('your.xlsx')
sheet = book.sheet_by_name('example')
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
# Profit !
print(data)
like image 117
Imad Salimi Avatar answered Oct 12 '22 08:10

Imad Salimi


If you're following the above comments and look into the xlrd package, can you try this and see if it works?

(based on what I found here: http://www.youlikeprogramming.com/2012/03/examples-reading-excel-xls-documents-using-pythons-xlrd/)

import xlrd
workbook = xlrd.open_workbook('my_workbook.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
curr_row = 0

#creates an array to store all the rows
row_array = []

while curr_row < num_rows:
    row = worksheet.row(curr_row)
    row_array += row
    curr_row += 1

print(row_array)
like image 22
David B. Avatar answered Oct 12 '22 08:10

David B.