【问题标题】:Count the frequency of each element categorical values in python [duplicate]计算python中每个元素分类值的频率[重复]
【发布时间】:2019-10-19 14:24:57
【问题描述】:

有没有简单的方法在 Python 中做到这一点?

例如我有:

x = np.array(['a', 'b', 'a', 'b', 'b', 'u'])

期望的结果:

[2, 3, 2, 3, 3, 1]

【问题讨论】:

  • 即使您的问题已关闭,您也可以选择答案。我建议这样做,因为 np.unique 的相对较新的参数使答案比接受的副本更有效。

标签: python numpy frequency


【解决方案1】:

使用np.unique 并启用return_countsreturn_inverse

_, inverse, count = np.unique(x, return_inverse=True, return_count=True)
result = count[inverse]

【讨论】:

  • 你错过了 return_count 参数
  • @tstanisl。哇。非常感谢:)
猜你喜欢
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多