Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Merge duplicate index into single index

Tags:

pandas

I have a simple data frame like this:

d1={'a':{'1998-01-01':10}}
d2={'b':{'1998-01-01':3}}

df=pd.DataFrame.from_dict(d1)
df=df.append(pd.DataFrame.from_dict(d2))
df.index=pd.to_datetime(df.index)

             a   b
1998-01-01  10 NaN
1998-01-01 NaN   3

I would like to have

             a   b
1998-01-01  10   3

Since 1998-01-01 share the index

like image 247
NinjaGaiden Avatar asked Mar 07 '16 22:03

NinjaGaiden


2 Answers

Or you can use groupby by index different way - with parameter level=0 with sum:

print df.groupby(level=0).sum()

             a  b
1998-01-01  10  3

Or better:

print df.sum(level=0)
like image 138
jezrael Avatar answered Mar 19 '23 23:03

jezrael


Alternatively you can try this (with your original data frame):

print(df)
print(df.groupby(df.index).sum())

Output:

             a   b
1998-01-01  10 NaN
1998-01-01 NaN   3
             a  b
1998-01-01  10  3
like image 30
MaxU - stop WAR against UA Avatar answered Mar 20 '23 00:03

MaxU - stop WAR against UA