Collect data onto one row using common ID in python

Viewed 36

I have a DataFrame that looks like this

ID   Location1 Location2
AAA  Here      Null
AAA  Null      There
BBB  Here      Null
BBB  Null      There

and what I would like is to do is pull everything for each ID onto one line to give the following

ID   Location1 Location2
AAA  Here      There
BBB  Here      There

I am thinking perhaps I might want to use groupby or transform?

1 Answers

If is possible get first non Null values per groups use DataFrame.replace with GroupBy.first:

df1 = df.replace('Null', np.nan).groupby('ID', as_index=False).first()
print (df1)
    ID Location1 Location2
0  AAA      Here     There
1  BBB      Here     There
Related