5

我有兴趣尽快将 numpy 数组转换为稀疏字典。让我详细说明:

给定数组:

numpy.array([12,0,0,0,3,0,0,1])

我希望制作字典:

{0:12, 4:3, 7:1}

如您所见,我们只是将序列类型转换为从非零索引到其值的显式映射。

为了使这更有趣,我提供了以下测试工具来尝试替代方案:

from timeit import Timer

if __name__ == "__main__":
  s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector =         numpy.random.poisson(0.1, size=10000);"

  ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )"
             , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )"
             , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )"
             , "n = vector > 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))"
             , "i = flatnonzero(vector); v = vector[vector > 0]; dict(izip(i,v))"
             , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )"
             , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )"
             , "dict( (i, x) for i,x in enumerate(vector) if x > 0);"
             ]
  for m in ms:
    print "  %.2fs" % Timer(m, s).timeit(1000), m

我正在使用泊松分布来模拟我有兴趣转换的数组类型。

到目前为止,这是我的结果:

   0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) )
   0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) )
   0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) )
   0.67s n = vector > 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))
   0.81s i = flatnonzero(vector); v = vector[vector > 0]; dict(izip(i,v))
   1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )
   1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )
   4.90s dict( (i, x) for i,x in enumerate(vector) if x > 0);

如您所见,我找到的最快的解决方案是

n = vector > 0;
i = numpy.arange(len(vector))[n]
v = vector[n]
dict(izip(i,v))

有更快的方法吗?

编辑:步骤

i = numpy.arange(len(vector))[n]

似乎特别笨拙——在只选择一些元素之前生成整个数组,特别是当我们知道它可能只有大约 1/10 的元素被选中时。我认为这可能还有待改进。

4

5 回答 5

3
>>> a=np.array([12,0,0,0,3,0,0,1])
>>> {i:a[i] for i in np.nonzero(a)[0]}
{0: 12, 4: 3, 7: 1}
于 2014-10-31T10:52:45.003 回答
0

使用 scipy 中的稀疏矩阵作为桥梁:

from scipy.sparse import *
import numpy
a=numpy.array([12,0,0,0,3,0,0,1])
m=csr_matrix(a)

d={}
for i in m.nonzero()[1]:
  d[i]=m[0,i]
print d
于 2011-06-01T09:24:59.757 回答
0

以下似乎是一个显着的改进:

i = np.flatnonzero(vector)
dict.fromkeys(i.tolist(), vector[i].tolist())

定时:

import numpy as np
from itertools import izip

vector = np.random.poisson(0.1, size=10000)

%timeit f = np.flatnonzero(vector); dict( izip( f, vector[f] ) )
# 1000 loops, best of 3: 951 µs per loop

%timeit f = np.flatnonzero(vector); dict.fromkeys(f.tolist(), vector[f].tolist())
# 1000 loops, best of 3: 419 µs per loop

我也尝试过scipy.sparse.dok_matrixpandas.DataFrame.to_dict但在我的测试中它们比原来的要慢。

于 2014-10-31T20:24:31.020 回答
0

您可以np.unique使用return_index=True

>>> import numpy as np

>>> arr = np.array([12,0,0,0,3,0,0,1])

>>> val, idx = np.unique(arr, return_index=True)
>>> mask = val != 0                                # exclude zero
>>> dict(zip(idx[mask], val[mask]))                # create the dictionary
{0: 12, 4: 3, 7: 1}

迭代lists 通常比numpy.arrays 更快,因此当您将它们转换为列表时可以更快tolist

>>> dict(zip(idx[mask].tolist(), val[mask].tolist()))

定时

对于短阵列,这种方法可能较慢,但根据我的时间安排,它比其他大阵列的方法更快:

import numpy as np
from scipy.sparse import csr_matrix

arr = np.random.randint(0, 10, size=10000)  # 10k items
arr[arr < 7] = 0                            # make it sparse

# ----------

%timeit {i:arr[i] for i in np.nonzero(arr)[0]}
# 3.7 ms ± 51 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# ----------

%%timeit

val, idx = np.unique(arr, return_index=True)
mask = val != 0
dict(zip(idx[mask].tolist(), val[mask].tolist()))

# 844 µs ± 42.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# ----------

%%timeit

m=csr_matrix(a)

d={}
for i in m.nonzero()[1]:
    d[i]=m[0,i]

# 1.52 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
于 2017-05-20T01:50:11.293 回答
-1

试过这个?

从 numpy 导入到哪里

i = 其中(向量 > 0)[0]

于 2009-06-26T10:15:58.173 回答