【问题标题】:Finding smallest numbers Python numpy list查找最小的数字 Python numpy 列表
【发布时间】:2020-05-27 23:46:17
【问题描述】:

我有一个 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 个最小幅度数字掩蔽为零来移除它们!

【问题讨论】:

  • 您要删除列表中每个元素的底部 20% 吗?
  • 在 pop 中删除数组中的那些元素(不可能,因为数组需要一个固定的形状)或用零替换它们?
  • @JohnyVaknin remove as in 将删除的数字/值掩码为零
  • @Guillaume 不,我想通过将列表变量“l”中包含的所有 np 数组的底部 20% 掩码为零来删除它们。

标签: python-3.x numpy


【解决方案1】:

您可以尝试以下方法。它查找阈值并在该值低于阈值时将就地列表更新为 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 

【讨论】:

    【解决方案2】:

    你可以用这个:

    p = 20 #percentile to remove
    lower = np.percentile(np.hstack([x.flatten() for x in l]), p)
    for x in l:
      x[x<lower] = 0
    

    您基本上将所有数字堆叠到单个数组中并使用np.percentile,找到 p% 下限的阈值,然后使用下限过滤数组。

    【讨论】:

    • 请查看发布的解决方案。如果这不是您要查找的内容,请澄清您在删除底部 p% 和非矩形数组(在 numpy 中不存在)后打算做什么。也许输入和期望输出的玩具示例将帮助我们更好地理解这个问题。谢谢
    • @Arun 感谢您澄清问题。我编辑了答案以满足您的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2013-11-06
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多