[英]Split one dataframe into multiple dataframes with same column header based on values
[英]How to split dataframe into multiple dataframes based on header rows
我需要根据数据帧中重新出现的标头行将数据帧分为3个唯一的数据帧。
我的数据框看起来像:
0 1 2 .... 14
0 Alert Type Response Cost
1 w1 x1 y1 z1
2 w2 x2 y2 z3
. . . . .
. . . . .
144 Alert Type Response Cost
145 a1 b1 c1 d1
146 a2 b2 c2 d2
我试图获取包含单词“ Alert”的索引编号,并将loc切片为子数据帧。
indexes = df.index[df.loc[df[0] == "Alert"]].tolist()
但这返回:
IndexError: arrays used as indices must be of integer (or boolean) type
关于该错误的任何提示,或者甚至还有我看不到的方法(例如,像group by这样的东西?)
谢谢你的帮助。
np.split
dfs = np.split(df, np.flatnonzero(df[0] == 'Alert')[1:])
查找df[0]
等于'Alert'
np.flatnonzero(df[0] == 'Alert')
忽略第一个,因为我们不需要一个空列表元素
np.flatnonzero(df[0] == 'Alert')[1:]
使用np.split
获取列表
np.split(df, np.flatnonzero(df[0] == 'Alert')[1:])
print(*dfs, sep='\n\n')
0 1 2 14
0 Alert Type Response Cost
1 w1 x1 y1 z1
2 w2 x2 y2 z3
0 1 2 14
144 Alert Type Response Cost
145 a1 b1 c1 d1
146 a2 b2 c2 d2
@piRSquared答案的效果很好,所以让我向您解释错误。
这是获取第一个元素为Alert
的索引的方法:
indexes = list(df.loc[df['0'] == "Alert"].index)
您的错误是由于df.index
是pandas.RangeIndex对象,因此无法进一步建立索引而引起的。
然后,您可以使用列表理解来拆分数据框,如下所示:
listdf = [df.iloc[i:j] for i, j in zip(indexes, indexes[1:] + [len(df)])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.