我正在嘗試處理一個 excel 檔案,以便以后可以使用每一行和每一列進行特定操作。
我的問題如下:
- 使用 Openpyxl 使我可以更輕松地加載檔案并能夠遍歷行
#reading the excel file
path = r'Datasets/Chapter 1/Table B1.1.xlsx'
wb = load_workbook(path) #loading the excel table
ws = wb.active #grab the active worksheet
#Setting the doc Header
for h in ws.iter_rows(max_row = 1, values_only = True): #getting the first row (Headers) in the table
header = list(h)
for sh in ws.iter_rows(min_row = 1 ,max_row = 2, values_only = True):
sub_header = list(sh)
#removing all of the none Values
header = list(filter(None, header))
sub_header = list(filter(None, sub_header))
#creating a list of all the rows in the excel file
row_list = []
for row in ws.iter_rows(min_row=3): #Iteration over every single row starting from the third row since first two are the headers
row = [cell.value for cell in row] #Creating a list from each row
row = list(filter(None, row)) #removing the none values from each row
row_list.append(row) #creating a list of all rows (starting from the 3d one)
colm = []
for col in ws.iter_cols(min_row=3,min_col = 1): #Iteration over every single row starting from the third row since first two are the headers
col = [cell.value for cell in col] #Creating a list from each row
col = list(filter(None, col)) #removing the none values from each row
colm.append(col) #creating a list of all rows (starting from the 3d one)
但同時(就我在檔案中讀到的而言),我無法對其進行可視化或對行或列進行直接操作。
- 雖然使用 Pandas 對行和列進行直接操作更有效,但我讀過不推薦迭代資料幀以獲取串列中的行,即使使用
df.iloc[2:]它不會給我同樣的結果結果(將每一行保存在特定串列中,因為標題始終存在)。但是,與 Openpyxl 不同的是,使用諸如df[col1]-df[col2]使用列名之類的東西對列進行直接操作要容易得多,這是我需要做的事情。(因為只是將所有列值放在串列中不會為我做)
所以我的問題是是否有一種解決方案可以只使用其中一個來做我想做的事情,或者如果同時使用它們并沒有那么糟糕,請記住我必須兩次加載 excel 檔案.
“提前致謝!”
uj5u.com熱心網友回復:
使用openpyxl讀取一個excel檔案,然后將行加載到pandas是沒有問題的:
pandas.DataFrame(row_list, columns=header)
您是對的,迭代DataFrameusing 索引非常慢,但您還有其他選擇:apply(), iterrows(),itertuples()
鏈接:在 Pandas DataFrame 中迭代行的不同方法
我還想指出,您的代碼可能沒有按照您的意愿行事。
list(filter(None, header))不僅過濾 None,而且過濾所有假值,例如0or""。- 這種過濾會移動列。例如,您有一行
[1, None, 3]和幾列['a', 'b', 'c']。通過過濾 None,您將獲得[1, 3]與列'a'和'b'.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366019.html
下一篇:有效地移位或大位向量
