将Excel文件作为lis导入Python

2024-04-25 09:43:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将一列10行作为列表导入Python。

所以我在excel中有:1,2,3,4,…,10 所有内容都写在第1-10行的A列。

现在我想将这些单元格导入到Python中,这样我的结果是:

list = ['One', 'Two', 'Three', 'Four', ..., 'Ten']

因为我对编程一窍不通,我不知道怎么做。所以请告诉我最简单的方法。我找到的所有教程,都没有给我想要的结果。 谢谢你

我正在使用Python2.7


Tags: 方法内容列表编程教程excelonelist
3条回答

我不确定您的数据是xlsx格式还是CSV格式。如果是XLSX,则使用this Python Excel tutorial。如果是CSV,就容易多了,您可以按照下面的代码片段进行操作。如果不想使用pandas,可以使用numpy库。使用下面的示例代码段获取CSV文件的顶行:

import numpy as np
csv_file = np.genfromtxt('filepath/relative/to/your/script.csv', 
                          delimiter=',', dtype=str)
top_row = csv_file[:].tolist()

这对于只有一列文本的文件有效。如果有更多的列,请使用下面的代码片段获取第一列。“0”表示第一列。

top_row = csv_file[:,0].tolist()

尽管pandas是一个很好的库,但对于简单的任务,您只需使用xlrd

import xlrd

wb = xlrd.open_workbook(path_to_my_workbook)
ws = wb.sheet_by_index(0)
mylist = ws.col_values(0)

注意,list不是Python中变量的好名字,因为这是内置函数的名字。

我建议安装熊猫。

pip install pandas

以及

import pandas
df = pandas.read_excel('path/to/data.xlsx') # The options of that method are quite neat; Stores to a pandas.DataFrame object
print df.head() # show a preview of the loaded data
idx_of_column = 5-1 # in case the column of interest is the 5th in Excel
print list(df.iloc[:,idx_of_column]) # access via index
print list(df.loc[['my_row_1','my_row_2'],['my_column_1','my_column_2']]) # access certain elements via row and column names
print list(df['my_column_1']) # straight forward access via column name

(签出pandas doc) 或者

pip install xlrd

代码

from xlrd import open_workbook
wb = open_workbook('simple.xls')
for s in wb.sheets():
  print 'Sheet:',s.name
  for row in range(s.nrows):
    values = []
    for col in range(s.ncols):
       values.append(s.cell(row,col).value)
    print ','.join(values)

(来自https://github.com/python-excel/tutorial/raw/master/python-excel.pdf的示例)

相关问题 更多 >