首页 > 解决方案 > 查找最小的数字 Python numpy 列表

问题描述

我有一个 Python 3 列表,其中包含任意数量的不同大小/形状的 numpy 数组。问题是将列表中最小的 p%(例如,p = 20%)的数字(就大小而言)删除为零。

示例代码:

l = []

l.append(np.random.normal(1.5, 1, size = (4, 3)))
l.append(np.random.normal(1, 1, size = (4, 4)))
l.append(np.random.normal(1.8, 2, size = (2, 4)))


for x in l:
    print(x.shape)

'''                                            
(4, 3)
(4, 4)
(2, 4)
'''

如何从“全局”“l”Python 列表中删除最小 p% 的数字,这意味着对于列表“l”中包含的所有 numpy 数组,它将删除最小数字的最小 p%(以量级)为零?

我正在使用 Python 3.8 和 numpy 1.18。

谢谢!

玩具示例:

l
'''
[array([[ 0.95400011,  1.95433152,  0.40316605],
        [ 1.34477354,  3.24612127,  1.54138912],
        [ 1.158594  ,  0.77954464,  0.4600395 ],
        [-0.03092974,  3.55349303,  0.85526191]]),
 array([[ 2.33613547,  0.12361808,  0.27620035,  0.70452795],
        [ 0.76989846, -0.28613191,  1.90050011,  2.73843595],
        [ 0.13510186,  0.91035556,  1.42402321,  0.60582303],
        [-0.13655066,  2.4881577 ,  2.0882935 ,  1.40347429]]),
 array([[-1.63365952,  1.2616223 ,  0.86784273, -0.34538727],
        [ 1.37161267,  2.4570491 , -0.72419948,  1.91873343]])]
'''

'l' 有 36 个数字。现在 36 的 20% = 7.2 或四舍五入 = 7。所以我们的想法是通过将 36 个数字中的 7 个最小幅度数字掩蔽为零来删除它们!

标签: python-3.xnumpy

解决方案


您可以尝试以下方法。它查找阈值并在该值低于阈值时将列表更新为 0。

如果您需要更多详细信息,请告诉我

import numpy as np

l = []

l.append(np.random.normal(1.5, 1, size = (4, 3)))
l.append(np.random.normal(1, 1, size = (4, 4)))
l.append(np.random.normal(1.8, 2, size = (2, 4)))

acc = []
p = 20 #percentile to update to 0

for x in l:
    acc.append(x.flatten())

threshold = np.percentile(np.concatenate(acc),p)

for x in l:
  x[x < threshold] = 0 

推荐阅读