【问题标题】:Create list of given length with given values - convert histogram to list of values创建具有给定值的给定长度列表 - 将直方图转换为值列表
【发布时间】:2016-09-30 12:26:54
【问题描述】:

我有一个直方图,我需要将其转换为我正在使用的另一款软件的单个实例列表:如果我有四个命中值“1”,三个命中值“2”,那么我的列表需要阅读[1,1,1,1,2,2,2]

我的直方图是由两个 numpy 数组组成的,它们被打包到一个名为 hist 的列表中,比如说。 hist[1] 中的数组存储我的 bin 边缘,hist[0] 中的数组存储每个 bin 的计数。

实现这种转换的一种非常粗略的方法是简单地运行以下代码:

inhist=[]
for i in range(len(hist[0])):
   for j in xrange(int(hist[0][i])):
       inhist.append(int(hist[1][i]))

有没有更好的方法来做到这一点?特别是当直方图变得非常大时,这可能不再是实现这一目标的最有效方法。看到我确切地知道我想要某个值多少次,我想知道我是否可以为自己节省所有循环?

我意识到做这整个事情通常会吃掉 RAM,而且效率不是很高,但是,唉,我目前别无选择。

编辑: print hist 返回:

[array([  0.00000000e+00,   1.83413630e+07,   1.74493106e+09,
          7.91390628e+10,   4.54474023e+11,   5.38810039e+11,
          3.01718080e+11,   1.38440761e+11,   6.17865624e+10,
          2.77457730e+10,   1.32412328e+10,   6.71579967e+09,
          3.35556066e+09,   2.00513046e+09,   1.18435261e+09,
          7.34440685e+08,   5.13846805e+08,   3.97894623e+08,
          1.97770421e+08,   1.11546165e+08,   6.63624300e+07,
          3.93196820e+07,   2.81038760e+07,   1.87733930e+07,
          1.57307950e+07,   1.55162030e+07,   1.38710060e+07,
          3.52969100e+06,   2.32881000e+05,   5.32210000e+04,
          1.59100000e+04,   4.89700000e+03,   1.61300000e+03,
          6.54000000e+02,   2.63000000e+02,   1.08000000e+02,
          3.10000000e+01,   8.00000000e+00,   4.00000000e+00,
          2.00000000e+00]),
 array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
        34, 35, 36, 37, 38, 39, 40], dtype=uint64)]

【问题讨论】:

    标签: python arrays list numpy


    【解决方案1】:

    那些i 索引基本上是元素范围,其长度范围为hist[0] 元素的数量,由第一个数组hist[0] 本身中存在的数字重复。使用这些我们只需索引到第二个数组hist[1] 即可为我们提供所需的输出。对于repeat 部分,我们可以使用np.repeat

    所以,我们会有一个实现,就像这样 -

    inhist = hist[1][np.arange(len(hist[0])).repeat(hist[0])]
    

    作为一种避免在 NumPy 数组中附加元素的矢量化解决方案,这应该非常有效。

    此外,如果我们使用浮点数的 NumPy 数组,我们可能需要转换为 int dtype。因此,输入hist[0].astype(int),如果输出也需要int dtype,请对其使用相同的转换,就像这样 -

    inhist = hist[1][np.arange(len(hist[0])).repeat(hist[0].astype(int))]
    

    【讨论】:

    • 我目前收到错误TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'。您能否修改代码以显示hist[0].astype(int) 位?
    • @P-M 更新了帖子。
    • 好吧,我就是这么想的。我现在得到一个内存错误:Traceback (most recent call last): File "path_length_distribution.py", line 24, in <module> inhist = hist[1][np.arange(len(hist[0])).repeat(hist[0].astype(int))] MemoryError任何想法为什么?
    • @P-M 您是否在这些输入上运行了您的原始代码?那你有没有遇到这样的内存错误?
    • 原代码目前运行愉快。好吧,我想是的,这需要很长时间,但我没有收到任何错误。
    猜你喜欢
    • 2019-06-24
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多