pandas 插入 NaN 的 Python 'map' 函数,可以改为返回原始值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35589820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 'map' function inserting NaN, possible to return original values instead?
提问by atkat12
I am passing a dictionary to the map
function to recode values in the column of a Pandas dataframe. However, I noticed that if there is a value in the original series that is not explicitly in the dictionary, it gets recoded to NaN
. Here is a simple example:
我正在将字典传递给map
函数以重新编码 Pandas 数据帧列中的值。但是,我注意到如果原始系列中有一个值在字典中没有明确显示,它会被重新编码为NaN
. 这是一个简单的例子:
Typing...
正在输入...
s = pd.Series(['one','two','three','four'])
...creates the series
...创建系列
0 one
1 two
2 three
3 four
dtype: object
But applying the map...
但是应用地图...
recodes = {'one':'A', 'two':'B', 'three':'C'}
s.map(recodes)
...returns the series
...返回系列
0 A
1 B
2 C
3 NaN
dtype: object
I would prefer that if any element in series s
is not in the recodes
dictionary, it remains unchanged. That is, I would prefer to return the series below (with the original four
instead of NaN
).
我希望如果系列中的任何元素s
不在recodes
字典中,它保持不变。也就是说,我更愿意返回下面的系列(使用原始four
而不是NaN
)。
0 A
1 B
2 C
3 four
dtype: object
Is there an easy way to do this, for example an option to pass to the map
function? The challenge I am having is that I can't always anticipate all possible values that will be in the series I'm recoding - the data will be updated in the future and new values could appear.
有没有一种简单的方法可以做到这一点,例如传递给map
函数的选项?我面临的挑战是我不能总是预测我正在重新编码的系列中所有可能的值——数据将在未来更新,新值可能会出现。
Thanks!
谢谢!