Python使用正则表达式(regex)创建新列的方法是通过pandas库中的str.extract()
函数。str.extract()
函数可以从一个字符串列中提取匹配正则表达式模式的内容,并创建一个新的列。
以下是使用regex创建新列的步骤:
import pandas as pd
import re
data = {'text': ['Hello, my email is example@example.com', 'Please contact me at 123-456-7890']}
df = pd.DataFrame(data)
str.extract()
函数创建新列:df['email'] = df['text'].str.extract(r'(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)')
df['phone'] = df['text'].str.extract(r'(\b\d{3}-\d{3}-\d{4}\b)')
在上述代码中,我们使用正则表达式模式提取电子邮件和电话号码,并将它们分别存储在email
和phone
列中。
print(df)
输出:
text email phone
0 Hello, my email is example@example.com example@example.com NaN
1 Please contact me at 123-456-7890 NaN 123-456-7890
可以看到,新的email
列包含提取的电子邮件地址,而phone
列包含提取的电话号码。
这种方法适用于任何需要使用正则表达式从文本中提取特定模式的情况,例如提取URL、日期、邮政编码等。
推荐的腾讯云相关产品:无
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云