使用regex替换Pandas数据框架中的值

使用regex替换Pandas数据框架中的值

在处理大型数据集时,它经常包含文本数据,在许多情况下,这些文本根本不漂亮。往往是以非常混乱的形式出现的,在我们对这些文本数据做任何有意义的事情之前,我们需要清理这些数据。大多数情况下,文本语料库非常大,我们无法手动列出所有我们想要替换的文本。所以在这些情况下,我们使用正则表达式来处理这些有一些模式的数据。

我们已经在上一篇文章中讨论了如何替换数据框架中的一些已知字符串值。在这篇文章中,我们将使用正则表达式来替换具有某些模式的字符串。

问题#1 :你得到一个数据框架,其中包含不同城市的各种事件的细节。对于那些以 “新 “或 “新 “开头的城市,将其改为 “新_”。

解决方案:我们将使用正则表达式来检测这些名字,然后我们将使用Dataframe.replace()函数来替换这些名字。

# importing pandas as pd
import pandas as pd
  
# Let's create a Dataframe
df = pd.DataFrame({'City':['New York', 'Parague', 'New Delhi', 'Venice', 'new Orleans'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
                    'Cost':[10000, 5000, 15000, 2000, 12000]})
  
# Let's create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
          pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
  
# Set the index
df.index = index_
  
# Let's print the dataframe
print(df)
Python

输出 :
使用regex替换Pandas数据框架中的值

现在我们将编写正则表达式来匹配字符串,然后我们将使用Dataframe.replace()函数来替换这些名字。

# replace the matching strings
df_updated = df.replace(to_replace ='[nN]ew', value = 'New_', regex = True)
  
# Print the updated dataframe
print(df_updated)
Python

输出 :
使用regex替换Pandas数据框架中的值
正如我们在输出中看到的,旧的字符串已经成功地被新的字符串替换。

问题2:给你一个数据框架,其中包含不同城市的各种事件的细节。某些城市的名称中包含一些括号内的额外细节。搜索这些名字并删除额外的细节。

解决方案:对于这项任务,我们将使用正则表达式编写我们自己的自定义函数来识别和更新这些城市的名称。此外,我们将使用Dataframe.apply()函数将我们的自定义函数应用于每一列的值。

# importing pandas as pd
import pandas as pd
  
# Let's create a Dataframe
df = pd.DataFrame({'City':['New York (City)', 'Parague', 'New Delhi (Delhi)', 'Venice', 'new Orleans'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy', 'Tech_Summit'],
                    'Cost':[10000, 5000, 15000, 2000, 12000]})
  
  
# Let's create the index
index_ = [pd.Period('02-2018'), pd.Period('04-2018'),
          pd.Period('06-2018'), pd.Period('10-2018'), pd.Period('12-2018')]
  
# Set the index
df.index = index_
  
# Let's print the dataframe
print(df)
Python

输出 :
使用regex替换Pandas数据框架中的值

现在我们将编写自己的自定义函数,以匹配城市名称中的描述。

# Importing re package for using regular expressions
import re
  
# Function to clean the names
def Clean_names(City_name):
    # Search for opening bracket in the name followed by
    # any characters repeated any number of times
    if re.search('\(.*', City_name):
  
        # Extract the position of beginning of pattern
        pos = re.search('\(.*', City_name).start()
  
        # return the cleaned name
        return City_name[:pos]
  
    else:
        # if clean up needed return the same name
        return City_name
          
# Updated the city columns
df['City'] = df['City'].apply(Clean_names)
  
# Print the updated dataframe
print(df)
Python

输出 :
使用regex替换Pandas数据框架中的值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程