如何基于列行拆分数据框 [英] How to split dataframe on based on columns row
本文介绍了如何基于列行拆分数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Excel文件,数据框有20行.在几行之后,又有一个列名行,我想根据列名行划分数据框.
I have one excel file , dataframe have 20 rows . after few rows there is again column names row, i want to divide dataframe based on column names row.
这是示例:
x
0
1
2
3
4
x
23
34
5
6
预期输出为:
df1
x
0
1
2
3
4
df2
x
23
34
5
6
推荐答案
Considering your column name is col
, you can first group the dataframe taking a cumsum
on the col
where the value equals x
by df['col'].eq('x').cumsum()
, then for each group create a dataframe by taking the values from the 2nd row of that group and the columns as the first value of that group using df.iloc[]
and save them in a dictionary:
d={f'df{i}':pd.DataFrame(g.iloc[1:].values,columns=g.iloc[0].values)
for i,g in df.groupby(df['col'].eq('x').cumsum())}
print(d['df1'])
x
0 0
1 1
2 2
3 3
4 4
print(d['df2'])
x
0 23
1 34
2 5
3 6
这篇关于如何基于列行拆分数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文