[英]Pandas loop through Excel sheets and append to df
我正在嘗試將 Excel 工作表和 append 數據從多張工作表循環到數據框中。
到目前為止我有:
master_df = pd.DataFrame()
for sheet in target_sheets:
df1 = file.parse(sheet, skiprows=4)
master_df.append(df1, ignore_index=True)
但是當我調用master_df.head()
它返回__
這些工作表上的數據采用相同的格式並且相互關聯。
所以我想像這樣加入他們:
第 1 頁包含:
A1
B1
C1
第 2 頁包含:
A2
B2
C2
第 3 頁:
A3
B3
C3
最終結果:
A1
B1
C1
A2
B2
C2
A3
B3
C3
我的邏輯是否正確,或者我該如何實現?
即使您不知道 excel文件中的確切sheet_names , 下面的代碼也能正常工作 。 你可以試試這個:
import pandas as pd
xls = pd.ExcelFile('myexcel.xls')
out_df = pd.DataFrame()
for sheet in xls.sheet_names:
df = pd.read_excel('myexcel.xls', sheet_name=sheet)
out_df.append(df) ## This will append rows of one dataframe to another(just like your expected output)
print(out_df)
## out_df will have data from all the sheets
如果這有幫助,請告訴我。
只需使用pd.concat()
:
pd.concat([pd.read_excel(file, sheet_name=sheet) for sheet in ['Sheet1','Sheet2','Sheet3']], axis=1)
例如,將產生:
A1 B1 C1 A2 B2 C2 A3 B3 C3
0 1 2 3 1 2 3 1 2 3
1 4 5 6 4 5 6 4 5 6
2 7 8 9 7 8 9 7 8 9
題中想要的output是通過設置axis=0得到的。
import pandas as pd
df2 = pd.concat([pd.read_excel(io="projects.xlsx", sheet_name=sheet) for sheet in ['JournalArticles','Proposals','Books']], axis=0)
df2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.