Home > Blockchain >  add in Pandas Series without sorting
add in Pandas Series without sorting

Time:01-24

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?

CodePudding user response:

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

CodePudding user response:

If the indices don't matter, you could simply add the values of the series, eg

c = a.values   b.values

This returns a numpy array:

array([    nan, 142000.,  32000.,  40000.])

It seems like you may also want to fill in 0 for nans -- in which case, try this:

c = a.fillna(0).values   b.fillna(0).values
  •  Tags:  
  • Related