5

Here is what we can read from the pandas map function documentation :

When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines missing (i.e. provides a method for default values), then this default is used rather than NaN

So I tried to apply this note with this code :

import pandas as pd 

class Missing_dict(dict) :

  def __init__(self,*arg,**kw):
      super(Missing_dict, self).__init__(*arg, **kw)

  def __missing__(self, key) :
    return key

md = Missing_dict({"a" : 0})

df = pd.DataFrame([{"key" : "a", "value" : 0}, {"key" : "b", "value" : 1}])

print (df)
print (df["key"].map(md))

But the result is not what I expect, in my case I want to map the data from one column, and if a value is not found in the dictionnary, then I would like this value as result (in other words, I would like the value if the key is in the dictionary, otherwise the key).

Where am I wrong ?

jsgounot
  • 709
  • 6
  • 12
  • 7
    try `df["key"].replace(md)` – EdChum May 24 '17 at 13:18
  • Thanks it works perfectly ! However isn't the previous code supposed to work too ? – jsgounot May 24 '17 at 13:24
  • `map` doesn't handle missing values in the way you want, it has a `na_action` param but this will either return `NaN` or return a single scalar value, what you're wanting to do is replace if the key is found, if not keep existing value which is what `replace` does – EdChum May 24 '17 at 13:58
  • Also are you sure you've sufficiently sub-classed the `dict` class? See https://stackoverflow.com/questions/3387691/how-to-perfectly-override-a-dict and https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict-and-override-getitem-setitem – EdChum May 24 '17 at 14:08
  • A similar subject (and the corresponding drawback) seems to be later discussed in the post below, but I can not call it a duplicate: https://stackoverflow.com/questions/67826593/pandas-map-dictionary-default-missing-value – Amin.A Apr 01 '22 at 20:16

0 Answers0