我在删除数字和括号以及 Python 中的内容时遇到问题。建议使用 str.replace。然而,这里的挑战是这些数字不是确定的数字。我只知道我需要删除任何数字,但我不确定它可能是什么。对于括号,我只知道我需要 remove () 以及里面的内容。但是,里面的内容也各不相同。例如,如果我有以下数据集:
import pandas as pd
a = pd.Series({'Country':'China 1', 'Capital': 'Bei Jing'})
b = pd.Series({'Country': 'United States (of American)', 'Capital': 'Washington'})
c = pd.Series({'Country': 'United Kingdom (of Great Britain and Northern Ireland)', 'Capital': 'London'})
d = pd.Series({'Country': 'France 2', 'Capital': 'Paris'})
e = pd.DataFrame([a,b,c,d])
现在在“国家/地区”列中,值为“中国 1”、“美国(美国)”、“英国(...)”和“法国 2”。替换/删除后,我想去掉所有数字和括号以及里面的内容,并希望 Column Country 中的值为 'China'、'United States'、'United Kingdom'、'France'。
请您参考如下方法:
您可以在此处使用 str.replace 和 regex。
series1.str.replace("^([a-zA-Z]+(?:\s+[a-zA-Z]+)*).*", r"\1")
看demo,可以替换成自己的系列和其他修改。
https://regex101.com/r/lIScpi/2
也可以直接修改frame。
a = pd.Series({'Country': 'China 1', 'Capital': 'Bei Jing'})
b = pd.Series({'Country': 'United States (of American)', 'Capital': 'Washington'})
c = pd.Series({'Country': 'United Kingdom (of Great Britain and Northern Ireland)', 'Capital': 'London'})
d = pd.Series({'Country': 'France 2', 'Capital': 'Paris'})
e = pd.DataFrame([a, b, c, d])
print e
e['Country'] = e['Country'].str.replace("^([a-zA-Z]+(?:\s+[a-zA-Z]+)*).*", r"\1")
print e
替换之前的输出。
Capital Country
0 Bei Jing China 1
1 Washington United States (of American)
2 London United Kingdom (of Great Britain and Northern ...
3 Paris France 2
替换后的输出
Capital Country
0 Bei Jing China
1 Washington United States
2 London United Kingdom
3 Paris France
