Liza
Liza

Reputation: 971

How to re-shape pandas data frame?

I have a following df:

  id   points
0 1    (2,3)
1 1    (2,4)
2 1    (4,6)
3 5    (6,7)
4 5    (8,9)

I am trying to obtain the following data frame:

  id    points
0 1     (2,3), (2,4), (4,6)
1 5     (6,7), (8,9)

Please suggest me to obtain the expected data frame.

Upvotes: 0

Views: 76

Answers (1)

piRSquared
piRSquared

Reputation: 294278

If points are tuple

df.groupby('id').points.apply(list).reset_index()

   id                    points
0   1  [(2, 3), (2, 4), (4, 6)]
1   5          [(6, 7), (8, 9)]

If you want an array

df.groupby('id').points.apply(lambda x: np.array(x.values.tolist())).reset_index()

   id                    points
0   1  [[2, 3], [2, 4], [4, 6]]
1   5          [[6, 7], [8, 9]]

If points are str

df.groupby('id').points.apply(', '.join).reset_index()

   id               points
0   1  (2,3), (2,4), (4,6)
1   5         (6,7), (8,9)

Upvotes: 3

Related Questions