Nan Values When Adding Two Columns
I have two dataframes with different indexing that I want to sum the same column from the two dataframes. I tried the following but gives NaN values result['Anomaly'] = df['Anomal
Solution 1:
Here is necessary align by datetimes
, so first use DataFrame.set_index
for DatetimeIndex
and then use Series.add
:
df = df.set_index('date')
tmp = tmp.set_index('date')
result = df['Anomaly'].add(tmp['Anomaly'], fill_value=0).reset_index()
Solution 2:
You can try this
pd.concat([df, tmp]).groupby('date', as_index=False)["Anomaly"].sum()
date Anomaly
0 2018-12-06 0
1 2019-01-07 1
2 2019-02-06 1
3 2019-03-06 0
4 2019-04-06 0
Solution 3:
res = pd.DataFrame({'date':df.date,'Anomaly':tmp.Anomaly.combine_first(df.Anomaly)})
print(res)
dateAnomaly02018-12-06 0.012019-01-07 1.022019-02-06 1.032019-03-06 0.042019-04-06 0.0
Solution 4:
You must first set correct indices on your dataframes, and then add using the date
indices:
tmp1 = tmp.set_index('date')
result= df.set_index('date')
result.loc[tmp1.index] += tmp1
result.reset_index(inplace=True)
Post a Comment for "Nan Values When Adding Two Columns"