python中的string np数组只取值的第一个字母
在下面的代码中,我想在 np 数组 capacity
中添加字符串“200”。
import numpy as np
capacity = np.repeat("", 6).reshape((6, 1))
capacity[0, 0] = "200"
然而返回结果总是这样:
array([['2'],
[''],
[''],
[''],
[''],
['']], dtype='<U1')
有谁知道为什么它只取第一个字母(数字)的原因?以及如何解决这个问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为创建数组时指定的数据类型。
- 表示该元素是长度为 0 或 1 的字符。这就是为什么当您尝试添加任意长度的字符串时,仅添加第一个字符。
因此,如果您想使用任何 len 字符串,则需要将 dtype 指定为对象:
祝您好运!
that's because of the dtype specified upon creation of the array.
<U1
- means that element is a char of length either 0, or 1. That's why when you try to add a string of an arbitrary length only the first char is added.So you need to specify the dtype to be an object if you want to work with any len strings:
Best of luck!