11

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

2 Answers 2

15

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

If need avoid that an all nan group (by index) gets transformed to zero add min_count=1, thanks @LukasS:

print (df.groupby(level=0, min_count=1).sum())
Sign up to request clarification or add additional context in comments.

6 Comments

you are creating 2 different dataframes. I have only a single one. I gave the code to show how to create my data. is there another way?
Sorry, I dont understand your question. Another answer is the best solution.
@pfabri Check MultiIndex, it means first or second level there, if no MultiIndex, then Index working same like first level of MultiIndex.
One should use min_count=1 to avoid that an all nan group (by index) gets transformed to zero.
@LukasS - thank you, added to answer.
|
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.