简体   繁体   English

按顺序按组拆分 DataFrame

[英]Split DataFrame by groups in order

I have a DataFrame with some measurements and one column for sensor position(L, C, R).我有一个带有一些测量值的 DataFrame 和一列用于传感器位置(L、C、R)。 I split my data into 3 smaller DataFrames by sensor position but the Problem I got the DataFrames not in correct order.我按传感器位置将数据拆分为 3 个较小的数据帧,但问题是我得到的数据帧顺序不正确。 My DataFrame:我的数据帧:

   t  position     x   y   z

0  0     L        ………………….
1  0.1   L        ………………….
2  0.2   L        ………………….
3  0     C        ………………….
4  0.1   C        ………………….
5  0.2   C        ………………….
6  0     R        ………………….
7  0.1   R        ………………….
8  0.2   R        ………………….

Expected:预期的:

DF1 for L & DF2 for C & DF3 for R

Got:得到了:

  DF1 for C & DF2 for L & DF3 for R

So I guess that the groupby reorder the splitted dataframes alphabetically not by their appearance in main DataFrame.所以我猜 groupby 按字母顺序重新排序拆分的数据帧,而不是它们在主 DataFrame 中的出现。 Do you have an idea how to get the correct order (order by appearance in data)?您是否知道如何获得正确的顺序(按数据中的外观排序)?

I used split by Group that has been mentioned in anthoer discussion here:我在这里使用了在 anthoer 讨论中提到的按组拆分:

def split(frame, group):
gb = frame.groupby(group)
return [gb.get_group(x).reset_index(level=0, drop=True) for x in gb.groups

I found a solution but not so elegant.我找到了一个解决方案,但不是那么优雅。 Dataframe would be splitted by masks rather groupby.数据帧将被掩码而不是 groupby 分割。 The masks should be applied in the desired order.应按所需顺序应用蒙版。

ind_l = df['position']=='L'
DF1 = df[ind_l].reset_index(drop=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM