使用collections.Counter
import collections as coll
data = {
'A': 'English',
'B': 'German',
'C': 'English'
}
print(coll.Counter(data.values()))
--output:--
Counter({'English': 2, 'German': 1})
使用pandas
:
import pandas as pd
data = {
'A': 'fr\n',
'B': 'de\n',
'C': 'fr\n',
'D': 'de\n',
'E': 'fr\n',
'F': 'en\n'
}
df = pd.DataFrame(
{
'id': list(data.keys()),
'lang': [val.rstrip() for val in data.values()],
}
)
print(df)
输出:
id lang
0 B de
1 A fr
2 F en
3 D de
4 E fr
5 C fr
grouped = df.groupby('lang')
print(grouped.size())
输出:
lang
de 2
en 1
fr 3
Respon SE发表评论
Plotting
:
import collections as coll
import matplotlib.pyplot as plt
import numpy as np
from operator import itemgetter
data = {
'A': 'fr\n',
'B': 'de\n',
'C': 'fr\n',
'D': 'de\n',
'E': 'fr\n',
'F': 'en\n'
}
counter = coll.Counter(
[val.rstrip() for val in data.values()]
)
langs, lang_counts = zip(
*sorted(counter.items(), key=itemgetter(1))
)
total_langs = sum(lang_counts)
bar_heights = np.array(lang_counts, dtype=float)/total_langs
x_coord_left_side_of_bars = np.arange(len(langs))
bar_width = 0.8
plt.bar(
x_coord_left_side_of_bars,
bar_heights,
bar_width,
)
plt.xticks(
x_coord_left_side_of_bars + (bar_width * 0.5), #position of tick marks
langs #labels for tick marks
)
plt.xlabel('review language')
plt.ylabel('% of all reviews')
x = plt.plot()
#plt.show() #Can use show() instead of savefig() until everything works correctly
plt.savefig('lang_plot.png')
情节:使用collections.Counter工作
字典方法。我现在有一个输出看起来像是一个字典,其中列出了各种语言的降序排列的实例数量。最后一步是,我需要将其显示在条形图中,以显示每种语言所代表的评论百分比。我假设这是一个matplotlib函数,但我不清楚如何从字典中提取数据来创建此图。 –
@AndrewSmith,计数器是无序的,这意味着你不能指望任何特定的密钥排序。请参阅我的答案底部的matplotlib示例。 – 7stud