該程式適用于讀取 excel 檔案的第一張表,而我試圖讀取 excel 檔案的所有表,但我無法讀取所有表。
import pandas as pd
class ExcelParser:
def __init__(self):
self.config = []
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None)
return raw_excel[conf].to_dict(orient='records')
if __name__ == "__main__":
conf = list(input("ENTER THE LIST HERE : ").split(','))
file_name = input("enter the full path to the file : ")
obj = ExcelParser()
obj.config = conf
print(obj.extract(file_name))
當我添加sheet_name = None閱讀 excel 行時,我遇到了這樣的錯誤,我無法找出錯誤是什么以及如何糾正錯誤。
(scrap-3-HFZx_P-py3.9) PS F:\mohan> & C:/Users/hp/AppData/Local/pypoetry/Cache/virtualenvs/scrap-3-HFZx_P-py3.9/Scripts/python.exe f:/mohan/main.py
ENTER THE LIST HERE : userid,city,state
enter the full path to the file : F:\\mis\\KB.xlsx
Traceback (most recent call last):
File "f:\mohan\main.py", line 16, in <module>
print(obj.extract(file_name))
File "f:\mohan\main.py", line 9, in extract
return raw_excel[conf].to_dict(orient='records')
TypeError: unhashable type: 'list'
uj5u.com熱心網友回復:
解決方案:
#output is nested lists of list of dictionaries
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None)
return [v[v.columns.intersection(conf)].to_dict(orient='records')
for k, v in raw_excel.items()]
說明:
如果使用sheet_name=None輸出是 DataFrames 的字典,這里raw_excel.
如果此處需要通過 dict 回圈,則將串列理解與 method 一起使用items,s 和for sv也是如此。valuekkey
如果conf使用了DataFrame 中的列,則僅過濾列Index.intersection。
Last 被使用to_dict,因此獲取每個 DataFrame 的字典串列。最終輸出,換句話說,return獲取字典串列的串列。
如果需要展平輸出是可能的使用這個解決方案:
flat_list = [item for sublist in t for item in sublist]
所以代碼被改變了:
#output is flatten list of dictionaries
def extract(self, file_name):
raw_excel=pd.read_excel(file_name,sheet_name=None)
return [x for k, v in raw_excel.items()
for x in v[v.columns.intersection(conf)].to_dict(orient='records')]
uj5u.com熱心網友回復:
這有點古怪,但是當你這樣做時
sheet_name=None,回傳的型別不是 pandasDataFrame而是dict. 我個人不喜歡用不同的引數改變回傳型別,但它就是這樣但是,這解決了型別錯誤的奧秘。因為你現在得到了一個 dict ,所以當你用一個串列子集時......它不能做那個操作并且會給你一個 Unhashable Type 錯誤。
我建議您有一個條件來檢查型別,然后進行一些額外的處理。
如果您需要詳細的型別檢查示例,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/408255.html
標籤:
