如何解决连接大CSV文件中的单词的最有效方法:熊猫还是Python标准库? CSV文件创建测试CSV文件:test_data.csv 读取CSV文件100次读取CSV文件的结果: pandas.Series.str.lower lower()
我正在尝试进行文本分析,并将我的数据收集到包含三列的CSV文档中。我试图将第二列中的所有文本合并为一个字符串,以执行一些词分析(词云,频率等)。我已经使用熊猫导入了CSV文件。在下面的代码中,data
是一个DataFrame
对象。
# Extract words from comment column in data
words = " "
for msg in data["comment"]:
msg = str(msg).lower()
words = words + msg + " "
print("Length of words is:",len(words))
使用word_cloud解析输出。
wordcloud = WordCloud(width = 3000,height = 2000,random_state=1,collocations=False,stopwords = stopwordsTerrier.union(stopwordsExtra)).generate(words)
CSV文件
rating,comment,ID
5,It’s just soooo delicIoUs but silly price and postage price,XXX1
5,love this salad dressing... One my kids will estv😊,XXX2
...
代码对于
我的问题是:有没有更有效的方法?
解决方法
Pandas解决方案(比标准库快2.5倍)
Pandas系列可以通过以下方式转换为字符串:pandas.Series.str.cat
data = pd.read_csv(file_path)
words = data["comment"].str.cat(sep=' ').lower()
Python标准库解决方案(较慢)
import csv
comment_list = []
with open(file_path,newline='') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
comment_list.append(row["comment"])
words = " ".join(comment_list).lower()
性能测试
使用标准库和pandas.read_csv
来读取CSV
使用pandas.read_csv()
的速度至少是Python标准库软件包csv
的2.5倍。
创建测试CSV文件:test_data.csv
import random
reviews = [
"Love this salad dressing... One my kids will estv😊","It’s just soooo delicious but silly price and postage price","The sitcome was entertaining but still a waste of time","If only I had ten stomaches to enjoy everything the buffet had to offer"
]
with open("test_data.csv","w") as file:
file.write("random_number,comment,index\n")
for i in range(10000):
file.write(f"{random.randint(0,9)},{random.choice(reviews)},{i}\n")
读取CSV文件100次
import csv
import pandas as pd
import timeit
def read_csv_stnd(file_path: str) -> str:
comment_list = []
with open(file_path,newline='') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
comment_list.append(row["comment"])
return " ".join(comment_list).lower()
def read_csv_pandas(file_path: str) -> str:
data = pd.read_csv(file_path)
return data["comment"].str.cat(sep=' ').lower()
data_file = "test_data.csv"
print(f"Time to run read_csv_stnd 100 times: {timeit.timeit(lambda: read_csv_stnd(data_file),number=100)}")
print(f"Time to run read_csv_pandas 100 times: {timeit.timeit(lambda: read_csv_pandas(data_file),number=100)}")
读取CSV文件的结果:
Time to run read_csv_stnd 100 times: 2.349453884999093
Time to run read_csv_pandas 100 times: 0.9676197949993366
标准库lower()
与pandas.Series.str.lower
使用标准库函数lower()
的速度大约是使用pandas.Series.str.lower
的5倍
pandas.Series.str.lower
>>> import pandas as pd
>>> import timeit
>>>
>>> s = pd.Series(['lower','CAPITALS','this is a sentence','SwApCaSe'])
>>> timeit.timeit(lambda: s.str.lower().str.cat(sep=' '),number=10000)
1.9734079910012952
lower()
>>> timeit.timeit(lambda: s.str.cat(sep=' ').lower(),number=10000)
0.3571630870010267
,
您可以尝试将单词附加到列表中,然后将列表转换为字符串,而不是在每次迭代中创建新的字符串。也许像这样:
words = [word.lower() for word in data["comment"]]
words = " ".join(words)
我已经用100,000个单词测试了它,它似乎比您目前使用的方法快15倍。当然,您可以在字符串的开头添加一个空格,或进行其他修改以符合您的确切要求。
,最明显的改进是如下连接python字符串(这是一种pythonic方式):
words = " ".join((str(msg).lower() for msg in data["comment"]))
由于字符串在python中是不可变的,因此您使用的方式会在每次串联时生成新的字符串。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。