How to select row information in dataframe over ID

nicolax9777 :

I'm new in python. I have a large dataframe as like that :

    ID  x   y
0   1   x1  y1
1   0   x2  y2
2   0   x3  y3
3   2   x4  y4
4   1   x5  y5
5   2   x6  y6

I would like to take couples of (x;y) between the IDs 1 and 2, in a dataframe like this :

    coordinates
0   (x1,y1), (x2,y2), (x3,y3), (x4,y4)
1   (x5,y5), (x6,y6)

I already tried a double for iteration but it is to long to compute. How can I get this thing?

jezrael :

One idea is create groups by each 1 starting values and aggregate custom lambda function for tuples:

df['new'] = (df['ID'] == 1).cumsum()
print (df)
   ID   x   y  new
0   1  x1  y1    1
1   0  x2  y2    1
2   0  x3  y3    1
3   2  x4  y4    1
4   1  x5  y5    2
5   2  x6  y6    2

df1 = (df.groupby('new')['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

Similar solution with no new column:

df1 = (df.groupby((df['ID'].rename('new') == 1).cumsum())['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

EDIT:

print (df)
   ID   x   y
0   1  x1  y1
1   0  x2  y2
2   0  x3  y3
3   2  x4  y4
4   0  x7  y7
4   0  x8  y8
4   1  x5  y5
5   2  x6  y6

g = df['ID'].eq(1).cumsum()
s = df['ID'].shift().eq(2).cumsum()

df = df[s.groupby(g).transform('min').eq(s)]
print (df)
   ID   x   y
0   1  x1  y1
1   0  x2  y2
2   0  x3  y3
3   2  x4  y4
4   1  x5  y5
5   2  x6  y6

df1 = (df.groupby((df['ID'].rename('new') == 1).cumsum())['x','y']
         .apply(lambda x: list(map(tuple, x.values.tolist())))
         .reset_index(name='coordinates'))
print (df1)
   new                               coordinates
0    1  [(x1, y1), (x2, y2), (x3, y3), (x4, y4)]
1    2                      [(x5, y5), (x6, y6)]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26598&siteId=1