给定测试数据集如下:
id company
0 1 xyz,ltd。
1 2 wall street english (bj)
2 3 James(sh)
3 4 NaN
4 5 黑石(上海)
我需要把中文标点符号换成对应的英文标点符号:(
表示(
,)
表示)
,.
表示。
,,
表示,
。
我试着用dd.company.str.replace('(', '(').replace(')', ')').replace('。', '.').replace(',', ',')
,它不是丙酮溶液,也不起作用。
退出:
0 xyz,ltd。
1 wall street english (bj)
2 James(sh)
3 NaN
4 黑石(上海)
Name: company, dtype: object
我怎么才能正确地更换它们?非常感谢。
发布于 2020-11-16 06:37:49
一种方法是使用2 lists
或字典,并将regex=True
传递给子字符串替换:
dd.company.replace(['(',')', '。', ','], ['(',')','.', ','], regex=True)
dd.company.replace({'(':')', '(':')', '。':'.', ',':','}, regex=True)
发布于 2020-11-16 11:42:36
我建议匹配任何标点符号(例如,使用匹配任何非单词和非空格字符的[^\w\s]
正则表达式),并在匹配中应用unidecode
:
import pandas as pd
import numpy as np
import unidecode
df = pd.DataFrame({'id':[1,2,3,4,5], 'company': ['xyz,ltd。', 'wall street english (bj)', 'James(sh)', np.NaN, '黑石(上海)']})
df['company'].str.replace(r'[^\w\s]+', lambda x: unidecode.unidecode(x.group()))
>>> df['company'].str.replace(r'[^\w\s]+', lambda x: unidecode.unidecode(x.group()))
0 xyz,ltd.
1 wall street english (bj)
2 James(sh)
3 NaN
4 黑石(上海)
Name: company, dtype: object
https://stackoverflow.com/questions/64853593
复制相似问题