在不获取NaN的情况下添加具有不同索引的 pandas 系列 [英] Adding pandas Series with different indices without getting NaNs

查看:59
本文介绍了在不获取NaN的情况下添加具有不同索引的 pandas 系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做我认为对熊猫来说是直截了当的操作,但是我似乎无法使其正常工作.

I'm trying to do what I think is a straight froward operation in pandas but I can't seem to make it work.

我有两个具有不同索引数量的pandas系列,如果它们共享一个索引,我想将它们加在一起,否则,我只想传递没有相应索引的值.

I have two pandas Series with different numbers of indices, I would like to add values together if they share an index, otherwise I would just like to pass the values that don't have corresponding indices along.

例如

Sr1 = pd.Series([1,2,3,4], index = ['A', 'B', 'C', 'D'])
Sr2 = pd.Series([5,6], index = ['A', 'C'])
Sr1        Sr2
A     1    A     5
B     2    C     6
C     3
D     4

Sr1 + Sr2Sr1.add(Sr2)给予

A     6
B   NaN
C     9
D   NaN

但是我想要的是

A     6
B     2
C     9
D     4

其中Sr1BD值刚刚传递.

有什么建议吗?

推荐答案

您可以使用fill_value:

>>> import pandas as pd
>>> Sr1 = pd.Series([1,2,3,4], index = ['A', 'B', 'C', 'D'])
>>> Sr2 = pd.Series([5,6], index = ['A', 'C'])
>>> Sr1+Sr2
A     6
B   NaN
C     9
D   NaN
>>> Sr1.add(Sr2, fill_value=0)
A    6
B    2
C    9
D    4

这篇关于在不获取NaN的情况下添加具有不同索引的 pandas 系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆