Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge rows based on index

I have a pandas dataframe like this,

Timestamp Meter1 Meter2
0         234    NaN
1         235    NaN
2         236    NaN
0         NaN    100
1         NaN    101
2         NaN    102

and I'm having trouble merging the rows based on the index Timestamp to something like this,

Timestamp Meter1 Meter2
0         234    100
1         235    101
2         236    102
like image 657
pranavhgupta Avatar asked Jun 07 '26 14:06

pranavhgupta


2 Answers

Option 0

df.max(level=0)

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0

Option 1

df.sum(level=0)

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0

Option 2
Disturbing Answer

df.stack().unstack()

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0

As brought up by @jezrael and linked to issue here

However, As I've understood groupby.first and groupby.last is that it will return the first (or last) valid value in the group per column. In other words, it is my belief that this is working as intended.

Option 3

df.groupby(level=0).first()

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0

Option 4

df.groupby(level=0).last()

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0

like image 177
piRSquared Avatar answered Jun 10 '26 08:06

piRSquared


Use groupby:

df.groupby(level=0).max()

OR

df.groupby('Timestamp').max()

Output

           Meter1  Meter2
Timestamp                
0           234.0   100.0
1           235.0   101.0
2           236.0   102.0
like image 35
Scott Boston Avatar answered Jun 10 '26 07:06

Scott Boston