How would I take an excel file and convert its columns into lists in Python?

旧街凉风 提交于 2019-12-04 14:54:48

问题


I had the following question. Namely, suppose I have an excel file with some names in the first row. Then the next however many rows are single letter entries (so "A", "B", "C" and so on).

My goal is to extract the column and make it into a list, so that, say, for column 1 the list would start in row 2, the next entry would be from row 3, and so on, until the end is reached.

How would I do that in Python?


回答1:


I used a module called xlrd.

Some information on that http://www.blog.pythonlibrary.org/2014/04/30/reading-excel-spreadsheets-with-python-and-xlrd/

And here is the package: https://pypi.python.org/pypi/xlrd

To exclude the first row, and make different lists for different columns you could do something like...

from xlrd import open_workbook

book = open_workbook("mydata.xlsx")
sheet = book.sheet_by_index(0) #If your data is on sheet 1

column1 = []
column2 = []
#...

for row in range(1, yourlastrow): #start from 1, to leave out row 0
    column1.append(sheet.cell(row, 0)) #extract from first col
    column2.append(sheet.cell(row, 1))
    #...

Put the index-1 of the last row that contains data in the 'yourlastrow' placeholder.




回答2:


I figured out the answer. Assuming the Excel file is Test.xlsx, we can translate the j-th column (excluding the first row) into list_j as follows:

book = xlrd.open_workbook("Test.xlsx")
sheet = book.sheet_by_index(0)

list_j = []

for k in range(1,sheet.nrows):
    list_j.append(str(sheet.row_values(k)[j-1]))


来源:https://stackoverflow.com/questions/37403460/how-would-i-take-an-excel-file-and-convert-its-columns-into-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!