我将如何获取一个 excel 文件并将其列转换为 Python 中的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37403460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:21:30  来源:igfitidea点击:

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

pythonexcellistimporttranslate

提问by Ryker

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).

我有以下问题。也就是说,假设我有一个 excel 文件,第一行中有一些名称。然后接下来的许多行是单字母条目(例如“A”、“B”、“C”等)。

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.

我的目标是提取该列并将其放入一个列表中,例如,对于第 1 列,该列表将从第 2 行开始,下一个条目将从第 3 行开始,依此类推,直到到达末尾。

How would I do that in Python?

我将如何在 Python 中做到这一点?

回答by Sonder

I used a module called xlrd.

我使用了一个名为xlrd的模块。

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

有关该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

这是包: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.

将包含数据的最后一行的 index-1 放在“yourlastrow”占位符中。

回答by Ryker

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:

我想出了答案。假设 Excel 文件是Test.xlsx,我们可以将第 j 列(不包括第一行)转换为 list_j 如下:

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]))