![](/img/trans.png)
[英]How to extract excel column data into python list using pandas from merged cell
[英]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.