python - 如何从 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()
解决方案
您的代码已经结构良好,但我仍然建议使用plt.bar
with 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()
推荐阅读
- sas - 在SAS中将数值变量转换为字符
- javascript - 基于SASS中的类名计算
- android - Firebase 实例 ID,获取许多不同授权实体的令牌抛出 INVALID_SENDER
- sql-server - 将 VARBINARY 转换为 Int 或 BigInt
- python - 解析查询结果以将其插入另一个数据库
- swift - 将多个 pickerView 选定值导出为 UILabel 上的数字
- python - 使用 python pandas 加入多个 CSV 文件
- python - Python中涉及多种模式的正则表达式匹配
- javascript - 如何对包含数组对象的对象进行字符串化?
- python - Django 条件创建