微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 使用pandas和matplotlib的单词频率

如何使用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线程中也有一个建议.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐