[英]How do I create several DataFrames for each sheet in an Excel file?
[英]How to read excel with several dataframes in one sheet and common index
我有一個 .xlsx 文件,其中包含多個數據幀,一張表中有公共索引。 一個例子:
什么是加載它並擁有兩個單獨的數據幀的好方法,一個是第一個 dataframe,第二個是第二個 dataframe,兩者都具有與 .xlsx 文件中相同的索引?
結果是:
df1 = pd.DataFrame(data={'col1': [aa, aa, aa], 'col2': [bb, bb, bb], 'col3': [cc, cc, cc]}, index=[0,1,2])
df2 = pd.DataFrame(data={'col1': [dd, dd, dd], 'col2': [ee, ee, ee], 'col3': [ff, ff, ff]},index=[0,1,2])
嘗試這樣的事情
import pandas as pd
df0 = pd.read_excel('mybook.xlsx', header=[0,1])
df0.head()
輸出:
Unnamed: 0_level_0 firstdataframe seconddataframe
index col1 col2 col3 col1 col2 col3
0 0 aa bb cc dd ee ff
1 1 aa bb cc dd ee ff
2 2 aa bb cc dd ee ff
所以,multindex 可能會有所幫助(header=[0,1] 表示第一行和第二行用作 col 索引)
然后,
df1=df0.loc[:,'firstdataframe']
df1
輸出
col1 col2 col3
0 aa bb cc
1 aa bb cc
2 aa bb cc
接着,
df2=df0.loc[:,'seconddataframe']
df2
輸出
col1 col2 col3
0 dd ee ff
1 dd ee ff
2 dd ee ff
閱讀https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
使用read_excel
中的usecols
參數
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.