替换 Python DataFrame 列中的字符

2024-04-14

简单的数据框replace下面显示的不起作用。
The NewPhone列包含与原始列相同的值。

import pandas as pd
SF = pd.read_csv(r"xxx.csv")
SF['NewPhone'] = SF['Phone'].replace("(",'xxx')
print(SF['NewPhone'])

replace http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html#pandas.Series.replace寻找完全匹配(默认情况下,除非你通过regex=True但你需要转义括号 - 请参阅@piRSquared的答案),你想要str.replace http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html#pandas.Series.str.replace:

SF['NewPhone'] = SF['Phone'].str.replace("(",'xxx')

这将用新字符串替换所有出现的传入字符串

Example:

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那么没有匹配发生:

In[22]:
df['phone'].replace("(",'xxx')

Out[22]: 
0    (999)-63266654
Name: phone, dtype: object

有关如何获取的信息,请参阅@piRSquared 的答案replace按预期工作(我不想蚕食他的答案)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

替换 Python DataFrame 列中的字符 的相关文章

随机推荐