pandas 用字典替换熊猫系列中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40075106/
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
Replace values in pandas Series with dictionary
提问by joga
I want to replace values in a pandas Series
using a dictionary. I'm following @DSM's accepted answerlike so:
我想Series
使用字典替换Pandas中的值。我正在关注@DSM接受的答案,如下所示:
s = Series(['abc', 'abe', 'abg'])
d = {'b': 'B'}
s.replace(d)
But this has no affect:
但这没有影响:
0 abc
1 abe
2 abg
dtype: object
The documentationexplains the required format of the dict for DataFrames
(i.e. nested dicts with top level keys corresponding to column names) but I can't see anything specific for Series
.
该文档解释了所需的 dict 格式DataFrames
(即具有与列名对应的顶级键的嵌套 dicts),但我看不到任何特定于Series
.
回答by MaxU
You can do it using regex=True
parameter:
您可以使用regex=True
参数来做到这一点:
In [37]: s.replace(d, regex=True)
Out[37]:
0 aBc
1 aBe
2 aBg
dtype: object
As you have already found out yourself- it's a RegEx replacement and it won't work as you expected:
正如您自己已经发现的那样- 它是一个 RegEx 替代品,它不会像您预期的那样工作:
In [36]: s.replace(d)
Out[36]:
0 abc
1 abe
2 abg
dtype: object
this is working as expected:
这是按预期工作的:
In [38]: s.replace({'abc':'ABC'})
Out[38]:
0 ABC
1 abe
2 abg
dtype: object