簡體   English   中英

如何從excel列中提取數據到Python中的列表?

[英]How to extract data from an excel column to a list in Python?

我試圖將數據從excel中的列提取到Python中的列表。 我有以下代碼:

#Extracting Labels
read = pd.read_excel('Test-data-results.xlsx', sheetname=0) # can also index sheet by name or fetch all sheets
labels = read['Labels'].tolist()
print(labels)

當我運行此代碼時,我得到一個關鍵錯誤:...。

 File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc

 File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc

 File "pandas/_libs/hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item

 File "pandas/_libs/hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item

 KeyError: 'Labels'

這是將數據追加到列表中的正確方法嗎? 有沒有辦法僅從列單元格字母(列A)中提取數據?

有沒有辦法僅從列單元格字母(列A)中提取數據?

Pandas允許按列名(也稱為標題)或整數位置建立索引。 由於A列是第一列,因此可以通過pd.DataFrame.iloc使用后一個選項:

read = pd.read_excel(...)
labels = read.iloc[:, 0].tolist()

如果您需要更具動態性的解決方案並且列數不超過26列,則可以使用字典映射:

from string import ascii_uppercase

d = {v: k for k, v in enumerate(ascii_uppercase)}
labels = read.iloc[:, d['A']].tolist()

但是,通常,如果您事先知道列名,則是個好主意。 發生您的錯誤是因為Pandas找不到'Labels''Labels'的列。 嘗試打印read.columns看到熊貓正在讀哪些列。

暫無
暫無

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

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