[英]How to split dataframe into multiple dataframes based on header rows
I need to split a dataframe into 3 unique dataframes based on a header-row reoccuring in the dataframe. 我需要根据数据帧中重新出现的标头行将数据帧分为3个唯一的数据帧。
My dataframe looks like: 我的数据框看起来像:
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
I was trying to get the index numbers containing the word "Alert" with loc to slice the dataframe into the sub dataframes. 我试图获取包含单词“ Alert”的索引编号,并将loc切片为子数据帧。
indexes = df.index[df.loc[df[0] == "Alert"]].tolist()
But this returns: 但这返回:
IndexError: arrays used as indices must be of integer (or boolean) type
Any hint on that error or is there even a way I don't see (eg smth like group by?) 关于该错误的任何提示,或者甚至还有我看不到的方法(例如,像group by这样的东西?)
Thanks for your help. 谢谢你的帮助。
np.split
dfs = np.split(df, np.flatnonzero(df[0] == 'Alert')[1:])
Find where df[0]
is equal to 'Alert'
查找df[0]
等于'Alert'
np.flatnonzero(df[0] == 'Alert')
Ignore the first one because we don't need an empty list element 忽略第一个,因为我们不需要一个空列表元素
np.flatnonzero(df[0] == 'Alert')[1:]
Use np.split
to get the list 使用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 answer works great, so let me just explain you error. @piRSquared答案的效果很好,所以让我向您解释错误。
This is how you can get the indexes where the first element is Alert
: 这是获取第一个元素为Alert
的索引的方法:
indexes = list(df.loc[df['0'] == "Alert"].index)
Your error arises from the fact that df.index
is a pandas.RangeIndex object, so it cannot be further indexed. 您的错误是由于df.index
是pandas.RangeIndex对象,因此无法进一步建立索引而引起的。
Then you can split your dataframe using a list comprehension like this: 然后,您可以使用列表理解来拆分数据框,如下所示:
listdf = [df.iloc[i:j] for i, j in zip(indexes, indexes[1:] + [len(df)])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.