簡體   English   中英

將 Excel 文件作為列表導入 Python

[英]Import Excel file in to Python as a list

我想將一列 10 行作為列表導入到 Python 中。

所以我在 excel 中舉例:一、二、三、四、...、十 所有寫在 A 列中的第 1-10 行。

現在我想將這些單元格導入 Python,這樣我的結果是:

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

由於我在編程方面完全是個菜鳥,所以我不知道該怎么做。 所以請告訴我最簡單的方法。 我找到的所有教程都沒有得到我想要的結果。 謝謝

我正在使用 Python 2.7

盡管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 中變量的好名稱,因為它是內置函數的名稱。

我不確定您的數據是 xlsx 格式還是 CSV 格式。 如果是 XLSX,請使用此 Python Excel 教程 如果是 CSV,則容易得多,您可以按照下面的代碼片段進行操作。 如果不想使用熊貓,可以使用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()

我建議安裝熊貓。

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

(結帳熊貓文檔)或

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

bonjour,je suis ududiant en mathes和je ne suis pas du tous for informatique mais je dois reussir python優秀出口商python 3. pouvez vous m'aidez merci。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM