用字典替换pandas系列中的值 [英] Replace values in pandas Series with dictionary

查看:408
本文介绍了用字典替换pandas系列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字典替换大熊猫Series中的值.我正在关注@DSM的接受的答案,如下所示:

I want to replace values in a pandas Series using a dictionary. I'm following @DSM's accepted answer like so:

s = Series(['abc', 'abe', 'abg'])
d = {'b': 'B'}
s.replace(d)

但这没有影响:

0    abc
1    abe
2    abg
dtype: object

文档解释了DataFrames的字典要求的格式(即嵌套的字典,其中的顶级键对应于列名),但是我看不到任何Series的特定内容.

The documentation explains 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.

推荐答案

您可以使用regex=True参数进行操作:

You can do it using regex=True parameter:

In [37]: s.replace(d, regex=True)
Out[37]:
0    aBc
1    aBe
2    aBg
dtype: object

您已经发现了自己 -它是RegEx的替代品,无法按预期工作:

As you have already found out yourself - it's a RegEx replacement and it won't work as you expected:

In [36]: s.replace(d)
Out[36]:
0    abc
1    abe
2    abg
dtype: object

这按预期工作:

In [38]: s.replace({'abc':'ABC'})
Out[38]:
0    ABC
1    abe
2    abg
dtype: object

这篇关于用字典替换pandas系列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆