【问题标题】:Sort each dictionary in a list of dictionaries, separately by its values - Python对字典列表中的每个字典进行排序,分别按其值 - Python
【发布时间】:2020-09-06 00:20:39
【问题描述】:

我正在尝试使用由词袋创建的词列表为调查响应集群制作标签。

每个单词列表都是一个字典,它是与其所在的集群对应的行的一部分。这些属性是 PANDAS 数据框的一部分。其他属性稍后将添加到数据框中,因此我需要保留行。

我想按每个字典中每个单词的计数按降序对每个字典进行排序。单词是键,计数是值。

这个数据框包括:

2列数据:df[['cluster#', 'dictionary']]

Cluster# = 一个整数

字典 = {word0:count0, word1:count1, ..., wordx:countx}

对于每个簇号,我希望相应的字典按计数降序排列。 (每个字典都有唯一数量的元素,由集群中唯一单词的数量定义。但这无关紧要)

如何使用 Python 做到这一点?我将使用单词列表作为集群的描述性标签。

【问题讨论】:

  • 你能让我们看看真正的字典吗?您所拥有的内容很难理解。
  • 不是实际对字典进行排序,而是可以按排序顺序访问它们吗?即类似for key in sorted(mydict.keys()):
  • 安,字典上面定义的很清楚。查看其中的内容不会比定义更好地帮助您理解该过程。它们因簇数而异,而且非常大。

标签: python pandas list dictionary


【解决方案1】:

我认为这就是你想要做的:

# First define a function that reverse-sorts a dictionary by values
def sort_dict(d):
    return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}

# Apply that function to the 'dictionary' column of your dataframe
df['dictionary'] = df['dictionary'].apply(sort_dict)

【讨论】:

  • @AlexJarvis 太棒了!如果您对解决方案感到满意,请考虑将答案标记为已接受。
猜你喜欢
  • 2011-02-22
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2021-08-25
  • 2014-01-23
  • 2010-09-09
相关资源
最近更新 更多