在pandas中的一张纸上构build数据框
我在Excel中有一个复杂的表单,我希望读入多个pandas.DataFrames
。
基本上,这里有3个dataframe。 一个用于DIRECTION_A
, DIRECTION_B
和TOTAL
。
如何告诉大pandas分别读取这些dataframe? 我可以使用iloc
来指定边界,但是由于我正在迭代许多不同的电子表格,因此存在不同位置的风险。
目前,我正在阅读所有这些列,跳过前7行:
tmp_df = pd.read_excel(file,sheetname=sheet_name,skiprows=7)
(样本数据)
我不认为你可以告诉大pandas单独阅读这些框架,但是他们在阅读后可以很容易地分开。
码:
def get_multi_frame_excel(*args, **kwargs): # read in the frame, with a multi level column index multi_frame = pd.read_excel(*args, header=[0, 1], **kwargs) # group the data by the top level column index, and store in dict frames = {name: group for name, group in multi_frame.groupby(level=0, axis=1)} # remove the top level index from the frames for frame in frames.values(): frame.columns = frame.columns.droplevel(level=0) # return a dict of frames return frames
testing代码:
frames = get_multi_frame_excel('SO_split_df.xlsx', skiprows=1) for name, frame in frames.items(): print('---') print(name) print(frame)
结果:
--- DIRECTION_A Time ABCDEFGH 00:00:00 0 0 0 0 0 0 0 0 00:15:00 0 0 0 0 0 0 0 0 00:30:00 0 0 0 0 0 0 0 0 .... 09:00:00 3 1 0 0 0 0 1 5 09:15:00 1 0 0 0 0 0 1 2 09:30:00 1 0 0 0 0 0 1 2 --- TOTAL Time ABCDEFGH 00:00:00 1 0 0 0 0 0 0 1 00:15:00 0 0 0 0 0 0 0 0 00:30:00 0 0 0 0 0 0 0 0 .... 09:00:00 7 1 0 0 0 0 1 9 09:15:00 4 0 0 0 0 0 3 7 09:30:00 3 0 0 0 0 0 1 4 --- DIRECTION_B Time ABCDEFGH 00:00:00 1 0 0 0 0 0 0 1 00:15:00 0 0 0 0 0 0 0 0 00:30:00 0 0 0 0 0 0 0 0 .... 09:00:00 4 0 0 0 0 0 0 4 09:15:00 3 0 0 0 0 0 2 5 09:30:00 2 0 0 0 0 0 0 2