Search code examples
pythonpandassortingadditionseries

add in Pandas Series without sorting


I want to add two Series in Pandas and I use add() function to do this like this:

import pandas as pd
import numpy as np
a = pd.Series([35000,71000,16000,5000],index=['Ohio','Texas','Oregon','Utah'])
b = pd.Series([np.nan,71000,16000,35000],index=['California', 'Texas', 'Oregon', 'Ohio'])
print(a.add(b, fill_value=0))

It prints :

California         NaN
Ohio           70000.0
Oregon         32000.0
Texas         142000.0
Utah            5000.0
dtype: float64

This method sort my indexes But I don't want to

What can I do or What method can I use?


Solution

  • You expected output is unclear, but assuming you want to keep the exact index of a, you could do:

    a.add(b.reindex_like(a), fill_value=0)
    

    output:

    Ohio       70000.0
    Texas     142000.0
    Oregon     32000.0
    Utah        5000.0
    dtype: float64