python - 使用 pandas 和 matplotlib 的词频

标签 python matplotlib pandas

如何使用 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

上面的代码创建了下图:

enter image description here

编辑:

您添加了一个次要条件,其中作者列可能包含多个以空格分隔的名称。以下代码处理此问题:

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 的词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22303554/

相关文章:

python - 在 argparse 中使用另一个选项值作为默认值

python - 使用相同的投影在图像上绘制线条

python - 如何使用 matplotlib 在轴上绘制带有参数的函数

python 多索引赋值

python线性回归按日期预测

python - 在 python 中获取 .gz 文件的未压缩大小

python - 使用元素的坐标捕获网页上元素的值

python - 使用 Python 从双指针 C++ 函数中读取字符串

python - 加载文件夹中的所有文件

python - Pandas - 根据特定列重新设置值