Home > Back-end >  How to merge rows with same id in python?
How to merge rows with same id in python?

Time:07-27

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

CodePudding user response:

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

CodePudding user response:

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
  • Related