【问题标题】:Replace values in pandas Series with dictionary用字典替换熊猫系列中的值
【发布时间】:2017-02-25 18:30:48
【问题描述】:

我想使用字典替换 pandas Series 中的值。我像这样关注@DSM 的accepted answer

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

但这没有效果:

0    abc
1    abe
2    abg
dtype: object

documentation 解释了DataFrames 所需的字典格式(即嵌套字典,其顶级键对应于列名),但我看不到任何特定于 Series 的内容。

【问题讨论】:

  • 您需要分配回结果或传递参数inplace=True 例如s = s.replace(d)s.replace(d, inplace=True),几乎所有 pandas 操作都会返回一个副本,因此您要么想要分配回去,要么在支持的情况下传递 inplace=True
  • 试试这个:s.replace(d, regex=True)
  • @EdChum, s.replace(d, inplace=True) - 没有做想要的替换 - 测试它...
  • @MaxU 那行得通-谢谢。隐藏的假设 - 我正在寻找正则表达式匹配 - 不是完全匹配。自己没有意识到。

标签: python pandas dictionary replace


【解决方案1】:

你可以使用regex=True参数来做到这一点:

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

正如您已经拥有 found out yourself - 它是 RegEx 的替代品,它不会像您预期的那样工作:

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

【讨论】:

  • 因为它假定您想用"B" 替换 "b",但值b 不在系列中。但是,b 包含在构成值的字符串中...
  • @juanpa.arrivillaga,是的,谢谢!我已经意识到了这一点。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2018-08-21
  • 2018-08-07
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
相关资源
最近更新 更多