Python 'map' 函数插入 NaN,是否可以 return 原始值代替?

Python 'map' function inserting NaN, possible to return original values instead?

我正在将字典传递给 map 函数以重新编码 Pandas 数据框列中的值。但是,我注意到如果原始系列中有一个值没有明确出现在字典中,它会被重新编码为 NaN。这是一个简单的例子:

正在输入...

s = pd.Series(['one','two','three','four'])

...创建系列

0      one
1      two
2    three
3     four
dtype: object

但是应用地图...

recodes = {'one':'A', 'two':'B', 'three':'C'}
s.map(recodes)

...return系列

0      A
1      B
2      C
3    NaN
dtype: object

我希望如果系列 s 中的任何元素不在 recodes 字典中,它会保持不变。也就是说,我更愿意return下面的系列(用原来的four代替NaN)。

0      A
1      B
2      C
3   four
dtype: object

有没有简单的方法可以做到这一点,例如传递给 map 函数的选项?我面临的挑战是,我不能总是预测我正在重新编码的系列中的所有可能值——数据将在未来更新,并且可能会出现新值。

谢谢!

使用replace代替map:

>>> s = pd.Series(['one','two','three','four'])
>>> recodes = {'one':'A', 'two':'B', 'three':'C'}
>>> s.map(recodes)
0      A
1      B
2      C
3    NaN
dtype: object
>>> s.replace(recodes)
0       A
1       B
2       C
3    four
dtype: object

如果您仍想使用 map 映射函数(在某些情况下可能比 replace 更快),您可以定义缺失值:

class MyDict(dict):
def __missing__(self, key):
    return key

s = pd.Series(['one', 'two', 'three', 'four'])

recodes = MyDict({
'one':'A',
'two':'B',
'three':'C'
})

s.map(recodes)

0       A
1       B
2       C
3    four
dtype: object