我正在用python制作一个2D numpy数组,如下所示
['0.001251993149471442' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'herfst'] ['0.002232327408019874' 'winter'] ['0.002232327408019874' 'winter']
我想从整个数组中获取最常用的字符串。 我已经找到了一些方法来实现这一点,但所有这些方法都有一个相同的问题,即它无法工作,因为数组中有两种数据类型
除了通过for循环和计数,还有没有更简单的方法从整个列(而不是行)中获取最常见的元素
您可以使用numpy和collections获得所有值的计数。您的问题不清楚2D列表中的数值实际上是数字还是字符串,但只要数值在第一位,单词在第二位,这两种情况都适用:
如果还想在计数中包括数字,只需跳过
del oneDim[0::2]
行不幸的是,
mode()
方法只存在于熊猫中,而不存在于Numpy中, 因此,第一步是展平阵列(arr)并将其转换为 泛美的系列:然后,如果您想找到最常见的字符串(请注意Numpy 阵列具有相同类型的所有元素),这是最直观的解决方案 是执行:
(s.mode() )
结果是:
但是如果你想省去可以转换成数字的字符串, 你需要一种不同的方法
不幸的是,您不能使用s.str.isnumeric(),因为它可以找到 仅由数字组成的字符串,但“数字”字符串包含 还有点
因此,您必须使用str.match和缩小系列(s) 然后调用模式:
这一次的结果是:
相关问题 更多 >
编程相关推荐