python中的string np数组只取值的第一个字母

发布于 2025-01-15 14:17:44 字数 352 浏览 2 评论 0 原文

在下面的代码中,我想在 np 数组 capacity 中添加字符串“200”。

import numpy as np
capacity = np.repeat("", 6).reshape((6, 1))
capacity[0, 0] = "200"

然而返回结果总是这样:

array([['2'],
       [''],
       [''],
       [''],
       [''],
       ['']], dtype='<U1')

有谁知道为什么它只取第一个字母(数字)的原因?以及如何解决这个问题?

In the following code, I want to add string "200" in the np array capacity.

import numpy as np
capacity = np.repeat("", 6).reshape((6, 1))
capacity[0, 0] = "200"

However the return result is always like:

array([['2'],
       [''],
       [''],
       [''],
       [''],
       ['']], dtype='<U1')

Does anyone know the reason why it only takes the first letter(number)? and how to solve the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀中猫帐中妖 2025-01-22 14:17:44

这是因为创建数组时指定的数据类型。
- 表示该元素是长度为 0 或 1 的字符。这就是为什么当您尝试添加任意长度的字符串时,仅添加第一个字符。

因此,如果您想使用任何 len 字符串,则需要将 dtype 指定为对象:

>>> capacity = np.array(['' for x in range(6)], dtype='object')
>>> capacity[0] = "200"
>>> capacity
array(['200', '', '', '', '', ''], dtype=object)

祝您好运!

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:

>>> capacity = np.array(['' for x in range(6)], dtype='object')
>>> capacity[0] = "200"
>>> capacity
array(['200', '', '', '', '', ''], dtype=object)

Best of luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文