Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

python - Adding pandas Series with different indices without getting NaNs

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

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.

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

A     6
B   NaN
C     9
D   NaN

But what I want is

A     6
B     2
C     9
D     4

where the B and D values for Sr1 are just passed along.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...