Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy.bincounts的反面?_Python_Numpy - Fatal编程技术网

Python numpy.bincounts的反面?

Python numpy.bincounts的反面?,python,numpy,Python,Numpy,我正在尝试创建一个Numpy优化版本的inverse。我意识到bincounts不是一对一的,所以让我们来谈谈最简单的版本 import numpy as np def bincounts_inverse(counts): list = [] dtype = np.min_scalar_type(counts.shape[0] - 1) for bin, count in enumerate(counts): ar = np.empty(count,

我正在尝试创建一个Numpy优化版本的inverse。我意识到
bincounts
不是一对一的,所以让我们来谈谈最简单的版本

import numpy as np


def bincounts_inverse(counts):
    list = []
    dtype = np.min_scalar_type(counts.shape[0] - 1)
    for bin, count in enumerate(counts):
        ar = np.empty(count, dtype=dtype)
        ar[:] = bin
        list.append(ar)

    return np.concatenate(list)
这可能是我目前对Numpy和Python所掌握的最好的知识了。当计数较高且箱子较低时,速度会非常快,但当计数相反时,速度会非常慢。它是渐近最优的,但可能不是你能做到的最好的

有没有更快的方法

下面是一个输入/输出示例

counts = np.array([3, 1, 0, 2, 5], np.uint8)
bincounts_inverse(counts) = np.array([0, 0, 0, 1, 3, 3, 4, 4, 4, 4, 4],
                                     dtype=np.uint8)

bincount
的倒数应该是-

样本运行-

In [22]: counts = np.array([3,0,2,1,0,2])

In [23]: list = []
    ...: dtype = np.min_scalar_type(counts.shape[0] - 1)
    ...: for bin, count in enumerate(counts):
    ...:     ar = np.empty(count, dtype=dtype)
    ...:     ar[:] = bin
    ...:     list.append(ar)
    ...: out = np.concatenate(list)

In [24]: out
Out[24]: array([0, 0, 0, 2, 2, 3, 5, 5], dtype=uint8)

In [25]: np.repeat(np.arange(len(counts)), counts)
Out[25]: array([0, 0, 0, 2, 2, 3, 5, 5])
另一种方法是使用非零索引,而sparsey
计数可能更有效-

idx = np.flatnonzero(counts!=0)
out = np.repeat(idx, counts[idx])

bincount
的倒数应该是-

样本运行-

In [22]: counts = np.array([3,0,2,1,0,2])

In [23]: list = []
    ...: dtype = np.min_scalar_type(counts.shape[0] - 1)
    ...: for bin, count in enumerate(counts):
    ...:     ar = np.empty(count, dtype=dtype)
    ...:     ar[:] = bin
    ...:     list.append(ar)
    ...: out = np.concatenate(list)

In [24]: out
Out[24]: array([0, 0, 0, 2, 2, 3, 5, 5], dtype=uint8)

In [25]: np.repeat(np.arange(len(counts)), counts)
Out[25]: array([0, 0, 0, 2, 2, 3, 5, 5])
另一种方法是使用非零索引,而sparsey
计数可能更有效-

idx = np.flatnonzero(counts!=0)
out = np.repeat(idx, counts[idx])

您能提供一些示例输入和预期输出吗?这会有帮助的ᴏʟᴅsᴘᴇᴇᴅ 我会把它添加到我的答案中,谢谢。你能提供一些示例输入和预期输出吗?这会有帮助的ᴏʟᴅsᴘᴇᴇᴅ 我会把这个加到我的回答中,谢谢。