Python 列表列表中元素的打印频率

Python 列表列表中元素的打印频率,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一份清单 my_list= [['UV'], ['SB'], ['NMR'], ['ISSN'], ['UK', 'USA'], ['MT'], ['UK'], ['UK'], ['ESP'], ['UK'], ['UK'], ['UK'], ['UK'], ['UK'], ['UK']] 我想根据频率从最频繁的项到较少频繁的项进行绘制 我在清点物品时

我有一份清单

my_list= [['UV'],
     ['SB'],
     ['NMR'],
     ['ISSN'],
     ['UK', 'USA'],
     ['MT'],
     ['UK'],
     ['UK'],
     ['ESP'],
     ['UK'],
     ['UK'],
     ['UK'],
     ['UK'],
     ['UK'],
     ['UK']]
我想根据频率从最频繁的项到较少频繁的项进行绘制

我在清点物品时发现了一些问题。我首先做的是将列表展平:

flattened = [] 
for sublist in my_list: 
    for val in sublist: 
        flattened.append(val) 
然后我试着数一数

from collections import Counter
import pandas as pd

counts = Counter(flattened)
df_ver = pd.DataFrame.from_dict(counts, orient='index')
df_ver.plot(kind='bar')

但是,它不起作用。我想它也不应该被分类。任何建议都将不胜感激。

让我们尝试纯Python:

counts = {}

for countries in my_list:
    for country in countries:
        counts[country] = counts.get(country,0) +1

sorted_counts = sorted(counts.items(), key=lambda i: (-i[1],i[0])) # sort by count and alphabetically if draw
# ktop = 10
# sorted_counts = sorted_counts[:ktop]
countries, counts = list(zip(*sorted_counts))

plt.bar(countries, counts);

让我们试试纯Python:

counts = {}

for countries in my_list:
    for country in countries:
        counts[country] = counts.get(country,0) +1

sorted_counts = sorted(counts.items(), key=lambda i: (-i[1],i[0])) # sort by count and alphabetically if draw
# ktop = 10
# sorted_counts = sorted_counts[:ktop]
countries, counts = list(zip(*sorted_counts))

plt.bar(countries, counts);
另一种选择:

df_ver =  df_ver.sort_values(0, ascending = False)
df_ver.plot(kind = "bar", legend = False)
另一种选择:

df_ver =  df_ver.sort_values(0, ascending = False)
df_ver.plot(kind = "bar", legend = False)
由于您使用计数器:

输出:

由于您使用计数器:

输出:

@Val请参阅更新的,带有扁平化list@Val请参阅中的注释代码updated@Val请参阅更新的,带有展平list@Val请参阅更新中的注释代码