替换Python DataFrame列中的字符 [英] Replace a character in a Python DataFrame column
本文介绍了替换Python DataFrame列中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面显示的简单数据框replace
无法正常工作.
NewPhone
列包含与原始列相同的值.
The simple dataframe replace
shown below is not working.
The NewPhone
column contains the same value as the original column.
import pandas as pd
SF = pd.read_csv(r"xxx.csv")
SF['NewPhone'] = SF['Phone'].replace("(",'xxx')
print(SF['NewPhone'])
推荐答案
replace
looks for exact matches (by default unless you pass regex=True
but you will need to escape the parentheses - see @piRSquared's answer), you want str.replace
:
SF['NewPhone'] = SF['Phone'].str.replace("(",'xxx')
它将用新字符串替换所有出现的传入字符串
which will replace all occurrences of the passed in string with the new string
示例:
In[20]:
df = pd.DataFrame({'phone':['(999)-63266654']})
df
Out[20]:
phone
0 (999)-63266654
In[21]:
df['phone'].str.replace("(",'xxx')
Out[21]:
0 xxx999)-63266654
Name: phone, dtype: object
如果我们尝试replace
,则不会发生匹配:
If we try replace
then no match occurs:
In[22]:
df['phone'].replace("(",'xxx')
Out[22]:
0 (999)-63266654
Name: phone, dtype: object
有关如何使replace
正常工作的信息,请参见@piRSquared的答案(我不想蚕食他的答案)
See @piRSquared's answer for how to get replace
to work as expected (I don't want to cannibalise his answer)
这篇关于替换Python DataFrame列中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文