蟒蛇爱好者,
计算numpy.character数组中字符出现的最快方法是什么。
我正在做以下事情:
In [59]: for i in range(10):
...: m = input("Enter A or B: ")
...: rr[0][i] = m
...:
Enter A or B: B
Enter A or B: B
Enter A or B: B
Enter A or B: A
Enter A or B: B
Enter A or B: A
Enter A or B: A
Enter A or B: A
Enter A or B: B
Enter A or B: A
In [60]: rr
Out[60]:
chararray([['B', 'B', 'B', 'A', 'B', 'A', 'A', 'A', 'B', 'A']],
dtype='<U1')
In [61]: %timeit a = rr.count('A')
12.5 µs ± 206 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [62]: %timeit d = len(a[a.nonzero()])
3.03 µs ± 54.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Run Code Online (Sandbox Code Playgroud)
我相信必须有更好的方法来快速和优雅地实现这一目标。
It\'s better to stick to regular NumPy arrays over the chararrays:
\n\n\n笔记:
\n\nchararray 类的存在是为了向后兼容 Numarray,不建议用于新开发。从 numpy 1.4 开始,如果需要字符串数组,建议使用 dtype object_、string_ 或 unicode_ 的数组,并使用 numpy.char 模块中的 free 函数进行快速向量化字符串操作。
\n
对于常规数组,我们提出两种方法。
\n\n方法#1
\n\n我们可以在与搜索元素进行比较后np.count_nonzero对这些进行计数: -True\'A\'
np.count_nonzero(rr==\'A\')\nRun Code Online (Sandbox Code Playgroud)\n\n方法#2
\n\n仅保留单个字符元素,我们可以通过使用dtype 查看它然后进行比较和计数chararray来更好地优化。uint8计数会快得多,因为我们将处理数字数据。实施将是 -
np.count_nonzero(rr.view(np.uint8)==ord(\'A\'))\nRun Code Online (Sandbox Code Playgroud)\n\n在 上Python 2.x,它将是 -
np.count_nonzero(np.array(rr.view(np.uint8))==ord(\'A\'))\nRun Code Online (Sandbox Code Playgroud)\n\n时间安排
\n\n原始样本数据的计时并缩放到10,000x缩放数据 -
# Original sample data\nIn [10]: rr\nOut[10]: array([\'B\', \'B\', \'B\', \'A\', \'B\', \'A\', \'A\', \'A\', \'B\', \'A\'], dtype=\'<U1\')\n\n# @Nils Werner\'s soln\nIn [14]: %timeit np.sum(rr == \'A\')\n100000 loops, best of 3: 3.86 \xc2\xb5s per loop\n\n# Approach #1 from this post\nIn [13]: %timeit np.count_nonzero(rr==\'A\')\n1000000 loops, best of 3: 1.04 \xc2\xb5s per loop\n\n# Approach #2 from this post\nIn [40]: %timeit np.count_nonzero(rr.view(np.uint8)==ord(\'A\'))\n1000000 loops, best of 3: 1.86 \xc2\xb5s per loop\n\n# Original sample data scaled by 10,000x\nIn [16]: rr = np.repeat(rr,10000)\n\n# @Nils Werner\'s soln\nIn [18]: %timeit np.sum(rr == \'A\')\n1000 loops, best of 3: 734 \xc2\xb5s per loop\n\n# Approach #1 from this post\nIn [17]: %timeit np.count_nonzero(rr==\'A\')\n1000 loops, best of 3: 659 \xc2\xb5s per loop\n\n# Approach #2 from this post\nIn [24]: %timeit np.count_nonzero(rr.view(np.uint8)==ord(\'A\'))\n10000 loops, best of 3: 40.2 \xc2\xb5s per loop\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1073 次 |
| 最近记录: |