Home > Software engineering >  How to concatenate pandas series such way
How to concatenate pandas series such way

Time:10-18

I need function: f(pd.Series(['a', 'b', 'c'], [[1, 2, 3]]), pd.Series(['b', 'c', 'd'], [[1, 2, 3]])) -> pd.Series(['a', 'b', 'c', 'd'], [[1, 3, 5, 3]]))

CodePudding user response:

Use groupby method of Series
Example:

a = pd.Series([1, 2, 3], ['a', 'b', 'c'])
b = pd.Series([1, 2, 3], ['b', 'c', 'd'])
c = pd.concat([a,b])
c.groupby(by=c.index).sum()

Result:

a    1
b    3
c    5
d    3
dtype: int64

CodePudding user response:

x = pd.Series([1, 2, 3], ['a', 'b', 'c'])
y = pd.Series([1, 2, 3], ['b', 'c', 'd'])

indices = set(list(x.index)   list(y.index))
x_re, y_re = x.reindex(indices).fillna(0), y.reindex(indices).fillna(0)
result = x_re   y_re
print(result)
b    3.0
d    3.0
a    1.0
c    5.0
dtype: float64
  • Related