首页 > 解决方案 > 如何从 csv 文件中绘制列的直方图

问题描述

示例文件看起来像这个x 轴应该有字母范围从 a-z+AZ 和 y 轴应该从内容列绘制它们各自的频率

import pandas as pd
import numpy as np
import string
from matplotlib import pyplot as plt
plt.style.use('fivethirtyeight')

col_list = ["tweet_id","sentiment","author","content"]
df = pd.read_csv("sample.csv",usecols=col_list)
freq = (df["content"])

frequencies = {}

for sentence in freq:
    for char in sentence:
        if char in frequencies:
            frequencies[char] += 1
        else:
            frequencies[char] = 1

frequency = str(frequencies)

bins = [chr(i + ord('a')) for i in range(26)].__add__([chr(j + ord('A')) for j in range(26)])


plt.title('data')
plt.xlabel('letters')
plt.ylabel('frequencies')
plt.hist(bins,frequency,edgecolor ='black')
plt.tight_layout()

plt.show()

标签: pythonpandasnumpymatplotlibhistogram

解决方案


您的代码已经结构良好,但我仍然建议使用plt.barwith letters onxticks而不是,因为在 x 轴上plt.hist使用它似乎更容易。chars我对此进行了评论,else以便除了所需的字母 ( a-zA-Z) 之外不会添加任何内容。还包括一个sorted命令,以提供让条按字母顺序或频率计数排序的选项。

sample.csv中使用的输入

    tweet_id  sentiment  author                                            content
0        NaN        NaN     NaN  @tiffanylue i know i was listenin to bad habit...
1        NaN        NaN     NaN  Layin n bed with a headache ughhhh...waitin on...
2        NaN        NaN     NaN                Funeral ceremony...gloomy friday...
3        NaN        NaN     NaN               wants to hang out with friends SOON!
4        NaN        NaN     NaN  @dannycastillo We want to trade with someone w...
5        NaN        NaN     NaN  Re-pinging @ghostridahl4: why didn't you go to...
6        NaN        NaN     NaN  I should be sleep, but im not! thinking about ...
...
...
# populate dictionary a-zA-Z with zeros
frequencies = {}
for i in range(26):
    frequencies[chr(i + ord('a'))] = 0
    frequencies[chr(i + ord('A'))] = 0

# iterate over each row of "content"
for row in df.loc[:,"content"]:
    for char in row:
        if char in frequencies:
            frequencies[char] += 1
        # uncomment to include numbers and symbols (!@#$...)
        # else:
        #     frequencies[char] = 1

# sort items from highest count to lowest
char_freq = sorted(frequencies.items(), key=lambda x: x[1], reverse=True)
# char_freq = sorted(frequencies.items(), key=lambda x: x, reverse=False)

plt.title('data')
plt.xlabel('letters')
plt.ylabel('frequencies')

plt.bar(range(len(char_freq)), [i[1] for i in char_freq], align='center')
plt.xticks(range(len(char_freq)), [i[0] for i in char_freq])

plt.tight_layout()

plt.show()

按字母顺序排序 sorted_by_count


推荐阅读