使用.str.replace()和.replace()更新pandas DataFrame [英] Update pandas DataFrame with .str.replace() vs .replace()

查看:429
本文介绍了使用.str.replace()和.replace()更新pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的pandas Dataframe df中有一列,其中包含一个带有一些尾随十六进制编码的NULL(\ x00)的字符串.至少我认为就是如此.当我尝试将其替换为:

I have a column in my pandas Dataframe df that contains a string with some trailing hex-encoded NULLs (\x00). At least I think that it's that. When I tried to replace them with:

df['SOPInstanceUID'] = df['SOPInstanceUID'].replace('\x00', '')

该列未更新.当我对

df['SOPInstanceUID'] = df['SOPInstanceUID'].str.replace('\x00', '')

工作正常. 这有什么区别? (SOPInstanceUID不是索引.)

it's working fine. What's the difference here? (SOPInstanceUID is not an index.)

谢谢

推荐答案

您未指定正则表达式或不需要完全匹配,因此可以使用str.replace

You did not specify a regex or require an exact match, hence str.replace worked

str.replace(old, new[, count])

返回该字符串的副本,其中所有出现的子字符串old都替换为new.如果给出了可选的参数count,则仅替换第一个出现的计数.

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad', axis=None)

parameter: to_replace : str, regex, list, dict, Series, numeric, or None

str或regex: str:与to_replace完全匹配的字符串将替换为value 正则表达式:与to_replace匹配的正则表达式将替换为值

str or regex: str: string exactly matching to_replace will be replaced with value regex: regexs matching to_replace will be replaced with value

它们实际上不在字符串中:您具有未转义的控制字符,Python使用十六进制表示法显示这些字符:

They're not actually in the string: you have unescaped control characters, which Python displays using the hexadecimal notation:

通过以下方式删除所有非单词字符:

remove all non-word characters in the following way:

re.sub(r'[^\w]', '', '\x00\x00\x00\x08\x01\x008\xe6\x7f')

这篇关于使用.str.replace()和.replace()更新pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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