更改二维 numpy 数组中单列的 dtype
我正在使用以下代码行创建一个充满零的二维数组:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想使用 结构化数组
有多种定义方法结构体中,我在这里定义了 4 个字段:一个包含 10 个字符的文本和三个浮点数(您可以写 float 而不是 f4)。
值得注意的是,出于数组内存管理的原因,必须指定数组的字符数。您将无法存储超过此最大长度的字符串。
每个字段都由字段名称引用,在本例中,将使用默认字段名称 f0 到 f3。例如,要获取整个第一列(文本列):
当然,您可以根据需要修改字段名称。
You might want to use structured arrays
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):
Of course, you can modifiy field names as you wish.