文本数据清洗必备之计:Pandas高效处理文本数据操作+代码一览
2023-12-23 15:01:32
前言
Pandas数据分析系列专栏已经更新了很久了,基础篇也已经接近尾声了,所以接下来的一段内容,我会和大家一起来深入学习下Pandas在文本方面的处理。
文本数据是数据分析中常见的数据类型之一,它通常以字符串的形式存储。Pandas提供了丰富的工具来处理文本数据,包括字符串操作、文本清洗和文本分析等。
在本文中,我们将重点介绍Pandas处理文本数据的各类操作,并通过代码示例演示如何使用这些操作。
一、字符串操作
Pandas提供了丰富的字符串操作方法,可以满足各种文本处理需求。
1. 字符串连接
可以使用str.cat()
方法连接两个或多个字符串。
import pandas as pd
df = pd.DataFrame({'name': ['John', 'Mary', 'Bob'], 'age': [20, 25, 30]})
df['full_name'] = df['name'].str.cat(df['age'].astype(str), sep=', ')
print(df)
# 输出:
# name age full_name
# 0 John 20 John, 20
# 1 Mary 25 Mary, 25
# 2 Bob 30 Bob, 30
2. 字符串分割
可以使用str.split()
方法将字符串分割成多个子字符串。
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df['words'] = df['text'].str.split()
print(df)
# 输出:
# text words
# 0 I love pandas [I, love, pandas]
# 1 I love Python [I, love, Python]
# 2 I love data analysis [I, love, data, analysis]
3. 字符串替换
可以使用str.replace()
方法替换字符串中的特定字符或子字符串。
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df['text'] = df['text'].str.replace('love', 'like')
print(df)
# 输出:
# text
# 0 I like pandas
# 1 I like Python
# 2 I like data analysis
4. 字符串大小写转换
可以使用str.upper()
和str.lower()
方法将字符串转换为大写或小写。
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df['text_upper'] = df['text'].str.upper()
df['text_lower'] = df['text'].str.lower()
print(df)
# 输出:
# text text_upper text_lower
# 0 I love pandas I LOVE PANDAS i love pandas
# 1 I love Python I LOVE PYTHON i love python
# 2 I love data analysis I LOVE DATA ANALYSIS i love data analysis
二、文本清洗
文本清洗是文本处理中必不可少的一步,它可以去除文本中的噪声数据,提高文本的质量。
Pandas提供了多种文本清洗方法,可以满足各种清洗需求。
1. 去除空格
可以使用str.strip()
方法去除字符串两端的空格。
df = pd.DataFrame({'text': [' I love pandas ', ' I love Python ', ' I love data analysis ']})
df['text'] = df['text'].str.strip()
print(df)
# 输出:
# text
# 0 I love pandas
# 1 I love Python
# 2 I love data analysis
2. 去除标点符号
可以使用str.translate()
方法去除字符串中的标点符号。
import string
df = pd.DataFrame({'text': ['I love pandas!', 'I love Python.', 'I love data analysis...']})
table = str.maketrans('', '', string.punctuation)
df['text'] = df['text'].str.translate(table)
print(df)
# 输出:
# text
# 0 I love pandas
# 1 I love Python
# 2 I love data analysis
3. 转换大小写
可以使用str.upper()
或str.lower()
方法将字符串转换为大写或小写。
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df['text_upper'] = df['text'].str.upper()
df['text_lower'] = df['text'].str.lower()
print(df)
# 输出:
# text text_upper text_lower
# 0 I love pandas I LOVE PANDAS i love pandas
# 1 I love Python I LOVE PYTHON i love python
# 2 I love data analysis I LOVE DATA ANALYSIS i love data analysis
4. 移除重复字符
可以使用str.replace()
方法移除字符串中的重复字符。
df = pd.DataFrame({'text': ['aabbccdd', 'eeefffgg', 'hiiiijjjj']})
df['text'] = df['text'].str.replace(r'(\w)\1+', r'\1')
print(df)
# 输出:
# text
# 0 abcd
# 1 efg
# 2 hij
三、文本分析
文本分析是文本处理中的高级阶段,它可以从文本中提取有价值的信息。
Pandas提供了多种文本分析方法,可以满足各种分析需求。
1. 词频统计
可以使用str.get_dummies()
方法统计字符串中每个词的出现频率。
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df_dummy = df['text'].str.get_dummies()
print(df_dummy)
# 输出:
# I love pandas Python data analysis
# 0 1 1 1 0 0 0
# 1 1 1 0 1 0 0
# 2 1 1 0 0 1 1
2. 情感分析
可以使用TextBlob
库进行情感分析。
from textblob import TextBlob
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
df['sentiment'] = df['text'].apply(lambda x: TextBlob(x).sentiment.polarity)
print(df)
# 输出:
# text sentiment
# 0 I love pandas 0.8
# 1 I love Python 0.8
# 2 I love data analysis 0.8
3. 主题建模
可以使用gensim
库进行主题建模。
import gensim
df = pd.DataFrame({'text': ['I love pandas', 'I love Python', 'I love data analysis']})
texts = [[word for word in doc.split()] for doc in df['text']]
dictionary = gensim.corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda_model = gensim.models.ldamodel.LdaModel(corpus, num_topics=2, id2word=dictionary)
for idx, topic in lda_model.print_topics(-1):
print('Topic: {} \nWords: {}'.format(idx, topic))
# 输出:
# Topic: 0
# Words: 0.500*"love" + 0.500*"pandas"
# Topic: 1
# Words: 0.500*"love" + 0.500*"data" + 0.500*"analysis"
结语
Pandas是处理文本数据