50

I am having some seemingly trivial trouble with numpy when the array contains string data. I have the following code:

my_array = numpy.empty([1, 2], dtype = str)
my_array[0, 0] = "Cat"
my_array[0, 1] = "Apple"

Now, when I print it with print my_array[0, :], the response I get is ['C', 'A'], which is clearly not the expected output of Cat and Apple. Why is that, and how can I get the right output?

Thanks!

4

6 回答 6

68

Numpy 要求字符串数组具有固定的最大长度。当您使用 创建一个空数组时dtype=str,它默认将此最大长度设置为 1。你可以看看你是否这样做my_array.dtype;它将显示“|S1”,意思是“一个字符的字符串”。对数组的后续分配将被截断以适应此结构。

您可以通过执行传递具有最大长度的显式数据类型,例如:

my_array = numpy.empty([1, 2], dtype="S10")

“S10”将创建一个长度为 10 的字符串数组。您必须决定有多大才能容纳您想要容纳的所有数据。

于 2012-12-05T06:40:21.873 回答
18

当我尝试使用非 ascii 字符时出现“编解码器错误”dtype="S10"

你还会得到一个带有二进制字符串的数组,这让我很困惑。

我认为最好使用:

my_array = numpy.empty([1, 2], dtype="<U10")

这里 'U10' 转换为“长度为 10 的 Unicode 字符串;小端格式”

于 2016-05-23T12:35:38.720 回答
10

numpy 字符串数组受其固定长度(默认长度为 1)的限制。如果您不确定您的字符串需要什么长度,您可以dtype=object为您的数据元素使用和获取任意长度的字符串:

my_array = numpy.empty([1, 2], dtype=object)

我知道这种方法可能存在效率缺陷,但我没有很好的参考来支持这一点。

于 2016-08-14T05:57:28.420 回答
0

如果是新来的人,我想现在还有另一种方法可以完成这项工作,只需要做一些工作:

my_array = np.full([1, 2], "", dtype=np.object)

使用np.full而不是 np.empty,并使用空字符串(类型为对象)创建数组。

于 2020-12-15T08:28:48.483 回答
0

另一种选择是初始化如下:

my_array = np.array([["CAT","APPLE"],['','']], dtype=str)

换句话说,首先你用你想要的东西编写一个常规数组,然后你把它变成一个 numpy 数组。但是,这会将您的最大字符串长度固定为初始化时最长字符串的长度。所以如果你要添加

my_array[1,0] = 'PINEAPPLE'

那么存储的字符串将是“PINEA”。

于 2017-07-03T17:19:44.963 回答
0

如果您正在执行 for 循环,最有效的方法是启动列表推导,这将允许您分配正确的内存。

data = ['CAT', 'APPLE', 'CARROT']
my_array = [name for name in data]
于 2020-03-29T02:30:07.923 回答