单词频率使用pandas和matplotlib

Dev*_*vEx 3 python matplotlib pandas

如何使用csv文件中的pandas和matplotlib绘制单词频率直方图(作者列)?我的csv就像:id,作者,标题,语言有时我在作者列中有多个作者用空格分隔

file = 'c:/books.csv'
sheet = open(file)
df = read_csv(sheet)
print df['author']
Run Code Online (Sandbox Code Playgroud)

Jan*_*cke 5

使用collections.Counter用于创建直方图数据,并按照给定的例子在这里,即:

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()
Run Code Online (Sandbox Code Playgroud)

有了这个测试文件:

$ 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
Run Code Online (Sandbox Code Playgroud)

上面的代码创建了以下图表:

在此输入图像描述

编辑:

您添加了辅助条件,其中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
Run Code Online (Sandbox Code Playgroud)

对于这个例子:

$ 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
Run Code Online (Sandbox Code Playgroud)

它打印

$ python test.py 
Counter({'peter': 3, 'bob': 2, 'harald': 2, 'marianne': 1})
Run Code Online (Sandbox Code Playgroud)

请注意,此代码仅起作用,因为字符串是可迭代的.

这个代码基本上没有pandas,除了领导DataFrame的CSV解析部分df.如果你需要pandas的默认情节样式,那么在提到的线程中也有一个建议.