如何创建任意长度字符串的 numpy 数组? [英] How to create a numpy array of arbitrary length strings?
问题描述
我是 Python 的完全新手,但似乎给定的字符串能够(有效地)是任意长度.即,您可以使用 string str
并不断添加:str += "some stuff..."
.有没有办法制作这样的字符串数组?
当我尝试这个时,每个元素只存储一个字符
strArr = numpy.empty(10, dtype='string')对于我在范围内(0,10)strArr[i] = "测试"
另一方面,我知道我可以初始化一个特定长度字符串的数组,即
strArr = numpy.empty(10, dtype='s256')
最多可存储 10 个字符串,最多 256 个字符.
您可以通过创建 dtype=object
数组来实现.如果您尝试将一个长字符串分配给普通的 numpy 数组,它会截断该字符串:
但是当您使用 dtype=object
时,您会得到一个 Python 对象引用数组.所以你可以拥有python字符串的所有行为:
确实,因为它是一个对象数组,您可以将任何种类的python对象分配给该数组:
<预><代码>>>>a[2] = {1:2, 3:4}>>>一种数组([苹果,foobar,{1:2,3:4}],dtype=object)然而,这抵消了使用 numpy 的许多好处,它如此之快,因为它适用于大量连续的原始内存块.使用 python 对象会增加很多开销.一个简单的例子:
<预><代码>>>>a = numpy.array(['abba' for _ in range(10000)])>>>b = numpy.array(['abba' for _ in range(10000)], dtype=object)>>>%timeit a.copy()100000 个循环,最好的 3 个:每个循环 2.51 us>>>%timeit b.copy()10000 个循环,最好的 3 个:每个循环 48.4 usI'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. i.e. you can take a string str
and keeping adding to it: str += "some stuff..."
. Is there a way to make an array of such strings?
When I try this, each element only stores a single character
strArr = numpy.empty(10, dtype='string')
for i in range(0,10)
strArr[i] = "test"
On the other hand, I know I can initialize an array of certain length strings, i.e.
strArr = numpy.empty(10, dtype='s256')
which can store 10 strings of up to 256 characters.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
这篇关于如何创建任意长度字符串的 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!