Hishi51
Hishi51

Reputation: 75

Split DataFrame by groups in order

I have a DataFrame with some measurements and one column for sensor position(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. 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. 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:

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

Upvotes: 0

Views: 165

Answers (1)

Hishi51
Hishi51

Reputation: 75

I found a solution but not so elegant. Dataframe would be splitted by masks rather groupby. The masks should be applied in the desired order.

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

Upvotes: 1

Related Questions