更改二维 numpy 数组中单列的 dtype

发布于 2024-09-26 21:46:30 字数 195 浏览 2 评论 0原文

我正在使用以下代码行创建一个充满零的二维数组:

MyNewArray=zeros([4,12],float)

但是,第一列需要填充字符串类型的文本数据,而所有其他列需要填充可操作的数字数据从数学上来说。

如何编辑上面的代码,以便矩阵中的第一列可以是字符串数据类型,同时保持所有其他列为浮点数?

I am creating a 2d array full of zeros with the following line of code:

MyNewArray=zeros([4,12],float)

However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data that can be manipulated mathematically.

How can I edit the code above so that the first column in the matrix can be of the string data type while keeping all the other columns as float?

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

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

发布评论

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

评论(1

呆萌少年 2024-10-03 21:46:30

您可能想使用 结构化数组

MyNewArray = zeros(12, dtype='S10,f4,f4,f4')

有多种定义方法结构体中,我在这里定义了 4 个字段:一个包含 10 个字符的文本和三个浮点数(您可以写 float 而不是 f4)。
值得注意的是,出于数组内存管理的原因,必须指定数组的字符数。您将无法存储超过此最大长度的字符串。

每个字段都由字段名称引用,在本例中,将使用默认字段名称 f0 到 f3。例如,要获取整个第一列(文本列):

MyNewArray['f0']

当然,您可以根据需要修改字段名称。

You might want to use structured arrays

MyNewArray = zeros(12, dtype='S10,f4,f4,f4')

There are several ways of defining the structure, here I have defined 4 fields: one text with 10 characters, and three floats (you could write float instead of f4).
It is important to note that the number of characters of the array has to be specified, for array memory management reasons. You won't be able to store strings longer than this maximum length.

Each field is referenced by a field name, in this case, default field names f0 to f3 will been used. For example, to get the whole first column (the textual one):

MyNewArray['f0']

Of course, you can modifiy field names as you wish.

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