vendredi 24 juin 2016

pandas series add fill_value from left side only

When applying an arithmetic operator via methods on a a pandas series or dataframe, you can pass an argument fill_value to specify how to handle missing values. http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.add.html

For example:

import pandas as pd
s1 = pd.Series([1, np.nan, 2])
s2 = pd.Series([1, 2, np.nan])

Just adding series s1 and s2 yields:

s1.add(s2)

0    2.0
1    NaN
2    NaN
dtype: float64

s1 is missing at s1.loc[1] and s2 is missing at s2.loc[2]. So at loc[[1, 2]] the add method produces missing. If we instead use the fill_value=0 argument:

s1.add(s2, fill_value=0)

0    2.0
1    2.0
2    2.0
dtype: float64

Which fills in missing values for s1 and s2.

Question: How do I fill in missing on left side only?

I'd expect a result that fills in the missing s1.loc[1] and returns missing at .loc[2]

0    2.0
1    2.0
2    NaN
dtype: float64

Aucun commentaire:

Enregistrer un commentaire