I'm trying to use the elements of the values column in the below data frame as keys in a dictionary.
In [1]: import numpy as np
...: import pandas as pd
...: rng = pd.date_range('2021-06-01', periods=4)
...: values = [1, -1, 0, np.nan]
...: df = pd.DataFrame(values, index=rng, columns=['values'])
In [2]: df
Out[2]:
values
2021-06-01 1.0
2021-06-02 -1.0
2021-06-03 0.0
2021-06-04 NaN
The goal is to map the elements of the values column to a set of new values in a separate column to produce the below data frame:
values new_values
2021-06-01 1.0 A
2021-06-02 -1.0 B
2021-06-03 0.0 C
2021-06-04 NaN D
So I created a dictionary with the keys as the elements in the values column.
In [3]: repl = {1: 'A', 0: 'B', -1: 'C',np.nan: 'D'}
In [4]: df['rule'] = df['Val'].apply(lambda x: repl[x])
'NaN', however, is creating a key error (despite it being hashable).
KeyError Traceback (most recent call last)
<ipython-input-143-2e9d3caa7f9c> in <module>
----> 1 df['rule'] = df['Val'].apply(lambda x: repl[x])
~/opt/miniconda3/envs/PyAlgo/lib/python3.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
4136 else:
4137 values = self.astype(object)._values
-> 4138 mapped = lib.map_infer(values, f, convert=convert_dtype)
4139
4140 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-143-2e9d3caa7f9c> in <lambda>(x)
----> 1 df['rule'] = df['Val'].apply(lambda x: repl[x])
KeyError: nan
Obviously, I can create the column manually for this simple example. However, this is just a minimally re-produceable example. In reality, I have a much larger data frame with many more potential keys.
Two questions:
- why does 'NaN' generate a key error despite it being hashable?
- what is the best way to solve this? One possibility is to set 'NaN' values to another value like -999 in the original data frame?