Python Pandas取代特殊字符

use*_*876 5 python tilde pandas

由于某种原因,我无法得到这个简单的陈述ñ.它似乎可以解决任何问题,但不喜欢这个角色.有任何想法吗?

DF['NAME']=DF['NAME'].str.replace("ñ","n")
Run Code Online (Sandbox Code Playgroud)

谢谢

jdo*_*dot 8

我假设你在这里使用Python 2.x这可能是一个Unicode问题.别担心,你并不孤单 - 一般来说unicode非常难,特别是在Python 2中,这就是为什么它在Python 3中已经成为标准.

如果你关心的只是ñ,你应该用UTF-8解码,然后只需要替换一个字符.

这看起来像下面这样:

DF['name'] = DF['name'].str.decode('utf-8').replace(u'\xf1', 'n')
Run Code Online (Sandbox Code Playgroud)

举个例子:

>>> "sureño".decode("utf-8").replace(u"\xf1", "n")
u'sureno'
Run Code Online (Sandbox Code Playgroud)

如果您的字符串已经是Unicode,那么您可以(并且实际上必须)跳过该decode步骤:

>>> u"sureño".replace(u"\xf1", "n")
u'sureno'
Run Code Online (Sandbox Code Playgroud)

请注意,此处u'\xf1'使用十六进制转义符来表示相关字符.

更新

我在评论中被告知这<>.str.replace是一个大熊猫系列方法,我没有意识到.对此的答案可能类似于以下内容:

DF['name'] = map(lambda x: x.decode('utf-8').replace(u'\xf1', 'n'), DF['name'].str)
Run Code Online (Sandbox Code Playgroud)

如果那个pandas对象是可迭代的,那么沿着那些行.

另一个更新

实际上,我发现您的问题可能与以下内容一样简单:

DF['NAME']=DF['NAME'].str.replace(u"ñ","n")
Run Code Online (Sandbox Code Playgroud)

请注意我是如何添加u字符串前面的以使其成为unicode的.

  • 这个问题是关于熊猫的.[str.replace](http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.core.strings.StringMethods.replace.html)是一个Series方法.虽然,我怀疑你可能已经死了替代代码点...... (2认同)