英文:
Strings being cut off when running numpy.insert()
问题
我遇到了一个问题,如果我有一个包含字符串的numpy数组,每次使用“insert”添加字符串时,它们的长度似乎受到数组中已有最长字符串的限制。
这是我的问题的简单演示:
import numpy as np
arr1 = np.array(["xxxxx", "yyyyy", "zzzzz"])
# insert at index 1
arr1 = np.insert(arr1, obj=1, values=["1234567890", "longer string"], axis=0)
print(arr1)
当我运行这段代码时,会打印出以下内容:
['xxxxx' '12345' 'longe' 'yyyyy' 'zzzzz']
有解决办法(或者我遗漏了什么)吗?
英文:
I'm getting an issue where if I have a numpy array with strings already inside it, every time I use insert
to add strings, their length seems to be limited by the longest string already inside the array.
Here's a simple demonstration of my issue:
import numpy as np
arr1 = np.array(["xxxxx", "yyyyy", "zzzzz"])
# insert at index 1
arr1 = np.insert(arr1, obj=1, values=["1234567890", "longer string"], axis=0)
print(arr1)
When I run this code, the following is printed:
['xxxxx' '12345' 'longe' 'yyyyy' 'zzzzz']
Is there a workaround (or something I'm missing) to this?
答案1
得分: 0
如果你在插入之前打印arr1.dtype
,你会看到dtype('<U5')
,这意味着字符串元素被限制在5
个字符。你需要将arr1
转换为通常的列表或对象类型:
arr1 = arr1.astype('object')
这样你就可以插入任意长度的字符串。
英文:
If you print arr1.dtype
before insert, you would see dtype('<U5')
, which means the string elements are capped at 5
characters. You would need to convert arr1
to a usual list or object type:
arr1 = arr1.astype('object')
so you can insert strings with any length.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论