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