正如您所看到的,我有3列:Name,Corp#和Dissagregation Category,它们共同作为每一行的唯一标识符。有两个超级标题,“英语/语言艺术分数”和“数学分数”。我想为每个标题创建两个单独的数据帧。这就是我到目前为止所做的:
App\SourceDetails
这将生成一个包含两个级别的数据框:df1 = pd.read_excel(file, header=None)
vals = df1.values
mux = pd.MultiIndex.from_arrays(df1.ffill(1).values[:2, 1:], names=[None, 'Name'])
df = pd.DataFrame(df1.values[2:, 1:], df1.values[2:, 0], mux)
和df['English/Language Arts Scores']
,其中包含标题下的列和“名称”作为索引。我希望这些数据框包括:Name,Copr#和Dissagregation Category作为列或索引。
这样做的最佳方法是什么?
修改
以下是我的数据的复制和可粘贴代码段:
df['Mathematics Scores']
我想要的输出应该如下所示:
English Math
A B C X Y X Y
ADAMS CENTRAL 0015 All Students 83 590 83 579
ADAMS CENTRAL 0015 General 1 0 *** 0 ***
ADAMS CENTRAL 0015 Total Gene 71 590 71 579
ADAMS West 0016 All Students 93 440 83 765
ADAMS West 0016 General 1 1 33 0 660
ADAMS West 0016 Total Gene 31 *** 46 572
答案 0 :(得分:1)
我们可以使用.loc
,读取文件,然后使用df = pd.read_excel('yourexcel.xlsx',
header=[0,1],
index_col=[0,1,2],
sheetname="Sheet1")
df.loc[:,'English']
Out[837]:
C X Y
ADAMS CENTRAL 15 All Students 83 590
General 1 0 ***
Total Gene 71 590
ADAMS West 16 All Students 93 440
General 1 1 33
Total Gene 31 ***
,将您需要的列级别切片
rename_axis
为了使其更加整洁,请添加df.loc[:,'English'].rename_axis(None,1)
Out[840]:
X Y
ADAMS CENTRAL 15 All Students 83 590
General 1 0 ***
Total Gene 71 590
ADAMS West 16 All Students 93 440
General 1 1 33
Total Gene 31 ***
vals = df.iloc[3:,:].values
df1 = pd.DataFrame(df.values[3:, 3:], df.values[3:, 0:3])
mux = pd.MultiIndex.from_arrays(df.ffill().ffill(1).values[1:3, 3:])
df1.columns=mux
df1.index = pd.MultiIndex.from_tuples(df1.index)
我们基于您的方法
drop table SALESORDERDETAIL;
create table SALESORDERDETAIL (
SONo CHAR(9), -- sales order number
ItemID char(8), -- item being ordered (finished goods)
SOquantity number(5), -- quantity of the item being ordered
Price Number(10,2), -- unit price of each item
subtotal Number(10,2), -- sales order detail (line) subtotal
constraint SOD_pk primary key(SONo,ItemID),
constraint SOD_FG_FK foreign key(ItemID) references FinishedGoods(itemid),
constraint SOD_SO_FK foreign key(SONo) references SalesOrders(SONo)
);
Insert into SALESORDERDETAIL (SONO,ITEMID,SOQUANTITY,PRICE,SUBTOTAL) values
('SO1000001','FG000001',100,10,'');
Insert into SALESORDERDETAIL (SONO,ITEMID,SOQUANTITY,PRICE,SUBTOTAL) values
('SO1000001','FG000002',50,2,'');
commit;