pandas 添加具有不同索引的熊猫系列而不会获得 NaN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12504493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:25:45  来源:igfitidea点击:

Adding pandas Series with different indices without getting NaNs

pythonpandas

提问by A Alstone

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.

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

For example

例如

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 + Sr2or Sr1.add(Sr2)give

Sr1 + Sr2Sr1.add(Sr2)给予

A     6
B   NaN
C     9
D   NaN

But what I want is

但我想要的是

A     6
B     2
C     9
D     4

where the Band Dvalues for Sr1are just passed along.

其中B和 的DSr1刚刚传递。

Any suggestions?

有什么建议?

回答by DSM

You could use fill_value:

你可以使用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

回答by kartik Garg

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

Sr2 = pd.Series([5,6,7], index = ['A', 'C','E'])
(Sr1+Sr2).fillna(Sr2).fillna(Sr1)

An alternative approach using fillna. It will work on all cases when indeces do not match too

使用 fillna 的另一种方法。当 indeces 不匹配时,它将适用于所有情况

回答by Nafeez Quraishi

A solution using fillna():

使用的解决方案fillna()

>>> 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).fillna(Sr1 + 0)
A    6.0
B    2.0
C    9.0
D    4.0