python – 使用pandas和matplotlib的单词频率
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用pandas和matplotlib的单词频率,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1630字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用pandas和matplotlib的单词频率](/upload/InfoBanner/zyjiaocheng/753/6600d43a92244378a9f9634657a14649.jpg)
如何使用csv文件中的pandas和matplotlib绘制单词频率直方图(作者列)?我的csv就像:id,作者,标题,语言
有时我在作者列中有多个作者以空格分隔
file = 'c:/books.csv'
sheet = open(file)
df = read_csv(sheet)
print df['author']
解决方法:
使用collections.Counter创建直方图数据,并按照给出的示例here,即:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Read CSV file, get author names and counts.
df = pd.read_csv("books.csv", index_col="id")
counter = Counter(df['author'])
author_names = counter.keys()
author_counts = counter.values()
# Plot histogram using matplotlib bar().
indexes = np.arange(len(author_names))
width = 0.7
plt.bar(indexes, author_counts, width)
plt.xticks(indexes + width * 0.5, author_names)
plt.show()
有了这个测试文件:
$cat books.csv
id,author,title,language
1,peter,t1,de
2,peter,t2,de
3,bob,t3,en
4,bob,t4,de
5,peter,t5,en
6,marianne,t6,jp
上面的代码创建了以下图表:
编辑:
您添加了辅助条件,其中author列可能包含多个以空格分隔的名称.以下代码处理此问题:
from itertools import chain
# Read CSV file, get
df = pd.read_csv("books2.csv", index_col="id")
authors_notflat = [a.split() for a in df['author']]
counter = Counter(chain.from_iterable(authors_notflat))
print counter
对于这个例子:
$cat books2.csv
id,author,title,language
1,peter harald,t1,de
2,peter harald,t2,de
3,bob,t3,en
4,bob,t4,de
5,peter,t5,en
6,marianne,t6,jp
它打印
$python test.py
Counter({'peter': 3, 'bob': 2, 'harald': 2, 'marianne': 1})
请注意,此代码仅起作用,因为字符串是可迭代的.
这个代码基本上没有pandas,除了领导DataFrame df的CSV解析部分.如果你需要pandas的默认绘图样式,那么mentioned线程中也有一个建议.
内容总结
以上是互联网集市为您收集整理的python – 使用pandas和matplotlib的单词频率全部内容,希望文章能够帮你解决python – 使用pandas和matplotlib的单词频率所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。