kronosapiens
kronosapiens

Reputation: 1441

'Dict.get()' equivalent for pandas Series?

Does anyone know if there's an equivalent for the Dict.get() method for pandas Series? I've got a series that looks like this:

In [25]: s1
Out[25]: 
a    1
b    2
c    3
dtype: int64

And I'd like to return a default value, such as 0, if I try to access an index that isn't there. For example, I'd like s1.ix['z'] to return 0 instead of KeyError. I know pandas has great support for dealing with missing values in other circumstances, but I couldn't find anything specifically about this.

Thank you!

Upvotes: 5

Views: 2129

Answers (2)

MattiH
MattiH

Reputation: 654

I couldn't make sense of the previous answers since they were missing the reference to the dict you use as source. Here is my answer, works for me at least

In[12]: s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'z'])
        my_dict = {'a': 1, 'b': 2, 'c': 3}
        result = s1.index.map(my_dict).fillna(0)
        new_series = pd.Series(result, index=s1.index)
        new_series

Out[13]: 
a    1.0
b    2.0
c    3.0
z    0.0
dtype: float64

Upvotes: 0

kronosapiens
kronosapiens

Reputation: 1441

As mentioned in the comments, pandas implements get directly for Series.

So s1.get('x', 0) would return 0

Upvotes: 4

Related Questions