【问题标题】:Find most common string in 2D numpy array在二维 numpy 数组中查找最常见的字符串
【发布时间】:2021-02-06 19:06:12
【问题描述】:

我正在 python 中制作一个 2D numpy 数组,看起来像这样

['0.001251993149471442' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'winter'] ['0.002232327408019874' 'winter']

我想从整个数组中获取最常见的字符串。 我确实已经找到了一些方法来做到这一点,但所有这些都有同样的问题,因为数组中有 2 种数据类型,所以它不起作用。

除了通过 for 循环运行并计数之外,还有更简单的方法可以从整列(而不是行)中获取最常见的元素吗?

【问题讨论】:

  • 请说明您尝试了什么以及问题所在。从外观上看,我看到了一个单一的数据类型,它是 str

标签: python arrays python-3.x numpy


【解决方案1】:

您可以使用 numpy 和集合来获取所有值的计数。从您的问题中不清楚您的二维列表中的数值实际上是数字还是字符串,但这适用于两者,只要数值是第一个并且单词是第二个:

import numpy
from collections import Counter

input1 = [['0.001251993149471442', 'herfst'], ['0.002232327408019874', 'herfst'], ['0.002232327408019874', 'herfst'], ['0.002232327408019874', 'winter'], ['0.002232327408019874', 'winter']]
input2 = [[0.001251993149471442, 'herfst'], [0.002232327408019874, 'herfst'], [0.002232327408019874, 'herfst'], [0.002232327408019874, 'winter'], [0.002232327408019874, 'winter']]

def count(input):
  oneDim = list(numpy.ndarray.flatten(numpy.array(input))) # flatten the list
  del oneDim[0::2]                                         # remove the 'numbers' (i.e. elements at even indices)
  counts = Counter(oneDim)                                 # get a count of all unique elements
  maxString = counts.most_common(1)[0]                     # find the most common one
  print(maxString)

count(input1)
count(input2)

如果您还想在计数中包含数字,只需跳过del oneDim[0::2] 这一行

【讨论】:

【解决方案2】:

很遗憾,mode() 方法只存在于 Pandas 中,而不存在于 Numpy 中, 所以第一步是展平您的数组 (arr) 并将其转换为 pandasonic 系列

s = pd.Series(arr.flatten())

那么如果你想找到最常见的字符串(并注意 Numpy 数组具有相同类型的所有元素),最直观的解决方案 是执行:

s.mode()[0]

(s.mode() 单独返回一个Series,所以我们只取初始元素 )。

结果是:

'0.002232327408019874'

但是,如果您想省略可转换为数字的字符串, 你需要一种不同的方法。

不幸的是,你不能使用 s.str.isnumeric() 因为它发现 由数字组成的字符串,但您的“数字”字符串包含 还有点。

所以你必须使用 str.match 来缩小你的系列 (s) 和 然后调用 mode:

s[~s.str.match('^[+-]?(?:\d|\d+\.\d*|\d*\.\d+)$')].mode()[0]

这次的结果是:

'herfst'

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2011-02-03
    • 1970-01-01
    • 2015-11-29
    • 2021-03-27
    • 2022-01-09
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多