在中组合多个正则表达式Pandas.DataFrame.str.更换?

2024-06-12 19:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在dataframe中有一列我想通过去掉括号来清理。在

1                          Auburn (Auburn University)[1]
2                 Florence (University of North Alabama)
3        Jacksonville (Jacksonville State University)[2]
4             Livingston (University of West Alabama)[2]
5               Montevallo (University of Montevallo)[2]
6                              Troy (Troy University)[2]
7      Tuscaloosa (University of Alabama, Stillman Co...
8                      Tuskegee (Tuskegee University)[5]
10         Fairbanks (University of Alaska Fairbanks)[2]
12            Flagstaff (Northern Arizona University)[6]

我使用unitowns['City'].str.replace('\(.*\)','').str.replace('\[.*\]','')来获得预期的结果,如下所示-

^{pr2}$

有没有办法把这些表达组合起来?此代码似乎不起作用->;unitowns['City'].str.replace('(\(.*\)) | (\[.*\])','')


Tags: ofcitydataframereplace括号struniversitytroy
1条回答
网友
1楼 · 发布于 2024-06-12 19:52:01

选项1
^{{cd2} 与其删除不相关的内容,不如提取相关内容呢?在

df.City.str.extract(r'(.*?)(?=\()', expand=False)

或者

^{pr2}$

^{3}$

您可能还希望在提取后去掉前导/尾随空格。您可以对结果调用str.strip

df.City = df.City.str.extract(r'(.*?)(?=\()', expand=False).str.strip()

或者

df.City = df.City.str.findall(r'(.*?)(?=\()').str[0].str.strip()

正则表达式详细信息

(      # capture group
.*?    # non-greedy matcher
)
(?=    # lookahead
\(     # opening parenthesis
)

选项2
str.split
如果你的城市名只有一个单词,str.split也可以。在

df.City.str.split('\s', 1).str[0]

0          Auburn
1        Florence
2    Jacksonville
3      Livingston
4      Montevallo
5            Troy
6      Tuscaloosa
7        Tuskegee
8       Fairbanks
9       Flagstaff
Name: City, dtype: object

选项3
str.replace
压缩你的连锁电话,你可以使用-

df['City'].str.replace(r'\(.*?\)|\[.*?\]', '').str.strip()

0          Auburn
1        Florence
2    Jacksonville
3      Livingston
4      Montevallo
5            Troy
6      Tuscaloosa
7        Tuskegee
8       Fairbanks
9       Flagstaff
Name: City, dtype: object

相关问题 更多 >