简体   繁体   English

添加两列时的 NaN 值

[英]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我尝试了以下但给出了 NaN 值

result['Anomaly'] = df['Anomaly'] + tmp['Anomaly']
df
    date           Anomaly
0 2018-12-06         0
1 2019-01-07         0
2 2019-02-06         1
3 2019-03-06         0
4 2019-04-06         0

tmp
    date           Anomaly
0 2018-12-06         0
1 2019-01-07         1
4 2019-04-06         0

result
    date           Anomaly
0 2018-12-06        0.0
1 2019-01-07        NaN
2 2019-02-06        1.0
3 2019-03-06        0.0
4 2019-04-06        0.0

What I want is actually:我想要的实际上是:

result
    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

Here is necessary align by datetimes , so first use DataFrame.set_index for DatetimeIndex and then use Series.add :这里有必要按datetimes对齐,所以首先使用DataFrame.set_index for DatetimeIndex然后使用Series.add

df = df.set_index('date')
tmp = tmp.set_index('date')
result = df['Anomaly'].add(tmp['Anomaly'], fill_value=0).reset_index()

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

combine_first() : combine_first()

res = pd.DataFrame({'date':df.date,'Anomaly':tmp.Anomaly.combine_first(df.Anomaly)})
print(res)

         date  Anomaly
0  2018-12-06      0.0
1  2019-01-07      1.0
2  2019-02-06      1.0
3  2019-03-06      0.0
4  2019-04-06      0.0

You must first set correct indices on your dataframes, and then add using the date indices:您必须首先在数据帧上设置正确的索引,然后使用date索引添加:

tmp1 = tmp.set_index('date')
result = df.set_index('date')
result.loc[tmp1.index] += tmp1
result.reset_index(inplace=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM