在pandas DataFrame中使用regex将一个字符串分割成若干列
给出一些包含多个值的字符串的混合数据,让我们看看如何使用regex划分字符串,并在Pandas DataFrame中制作多个列。
方法1
在这个方法中,我们将使用re.search(pattern, string, flags=0) 。这里pattern指的是我们要搜索的模式。它接收了一个有以下值的字符串。
- \匹配字母数字字符
- \d匹配数字,也就是0-9
- \匹配空白字符
- \匹配非空白字符
- 匹配任何字符,除了换行字符 (n)。
- 匹配一个模式的0个或多个实例
# import the regex library
import pandas as pd
import re
# Create a list with all the strings
movie_data = ["Name: The_Godfather Year: 1972 Rating: 9.2",
"Name: Bird_Box Year: 2018 Rating: 6.8",
"Name: Fight_Club Year: 1999 Rating: 8.8"]
# Create a dictionary with the required columns
# Used later to convert to DataFrame
movies = {"Name":[], "Year":[], "Rating":[]}
for item in movie_data:
# For Name field
name_field = re.search("Name: .*",item)
if name_field is not None:
name = re.search('\w*\s\w*',name_field.group())
else:
name = None
movies["Name"].append(name.group())
# For Year field
year_field = re.search("Year: .*",item)
if year_field is not None:
year = re.search('\s\d\d\d\d',year_field.group())
else:
year = None
movies["Year"].append(year.group().strip())
# For rating field
rating_field = re.search("Rating: .*",item)
if rating_field is not None:
rating = re.search('\s\d.\d',rating_field.group())
else:
rating - None
movies["Rating"].append(rating.group().strip())
# Creating DataFrame
df = pd.DataFrame(movies)
print(df)
输出:
解释:
- 在上面的代码中,我们使用for循环来迭代电影数据,这样我们可以依次处理每部电影。我们创建了一个字典,movies,它将保存每个细节的所有细节,如评级和名称。
- 然后我们使用re.search()函数找到整个Name字段。.表示除n以外的任何字符,而*则将其延伸到行尾。将其分配给变量name_field 。
- 但是,数据并不总是简单明了的。它可能包含意外的情况。例如,如果没有Name: 字段怎么办?脚本会抛出一个错误并中断。我们在这种情况下预先阻止错误的发生,并检查非无的情况。
- 我们再次使用re.search()函数从name_field中提取最终需要的字符串。对于这个名字,我们用 \w* 表示第一个词, \s 表示中间的空格, \w* 表示第二个词。
- 对年份和等级做同样的处理,得到最后所需的字典。
方法2
为了分解字符串,我们将使用Series.str.extract(pat, flags=0, expand=True) 函数。这里pat指的是我们要搜索的模式。
import pandas as pd
dict = {'movie_data':['The Godfather 1972 9.2',
'Bird Box 2018 6.8',
'Fight Club 1999 8.8'] }
# Convert the dictionary to a dataframe
df = pd.DataFrame(dict)
# Extract name from the string
df['Name'] = df['movie_data'].str.extract('(\w*\s\w*)', expand=True)
# Extract year from the string
df['Year'] = df['movie_data'].str.extract('(\d\d\d\d)', expand=True)
# Extract rating from the string
df['Rating'] = df['movie_data'].str.extract('(\d\.\d)', expand=True)
print(df)
输出: