0

I have a pandas DataFrame with the following property, How Can I merge rows with same id in python?

id test1 test2
one 10
one 30
two 3
three 10 5

what I want:

id test1 test2
one 10 30
two 3
three 10 5
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
user12217822
  • 292
  • 1
  • 5
  • 16
  • I think your question is something like [this](https://stackoverflow.com/q/46826773/12727539). – mo1ein Jul 26 '22 at 21:05

2 Answers2

0

Here is one way:

df = df.groupby('id', sort=False).max().reset_index()

Input:

      id  test1  test2
0    one   10.0    NaN
1    one    NaN   30.0
2    two    NaN    3.0
3  three   10.0    5.0

Output:

      id  test1  test2
0    one   10.0   30.0
1    two    NaN    3.0
2  three   10.0    5.0
constantstranger
  • 9,176
  • 2
  • 5
  • 19
0

You can do groupby.first to merge your same id into a row.

df.groupby('id', sort=False).first()
Out[18]: 
       test1  test2
id                 
one     10.0   30.0
two      NaN    3.0
three   10.0    5.0