更改numpy数组中特定值的dtype? [英] Change dtype for particular values in numpy array?

查看:142
本文介绍了更改numpy数组中特定值的dtype?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组x,维度=(20,4),其中只有第一行和第一列是真实的字符串值(字母),其余的值是数字,其类型分配为字符串.我想将这些数字值更改为浮点型或整数型.

I have a numpy array x, dimensions = (20, 4), in which only the first row and column are real string values (alphabets) and rest of the values are numerals with their types allocated as string. I want to change these numeral values to float or integer type.

我尝试了一些步骤:

a.我制作了数组的第一行和第一列的副本作为单独的变量:

a. I made copies of first row and column of the array as separate variables:

x_row = x[0]
x_col = x[:,0]

然后从原始数组x中删除它们(使用numpy.delete()方法),并通过应用对每个值进行迭代的for循环来转换剩余值的类型.但是,当我使用numpy.vstack()numpy.hstack()堆栈回复制的行和列时,所有内容再次转换为字符串类型.因此,不确定为什么会这样.

Then deleted them from the original array x (using numpy.delete() method) and convertd the type of remaining values by applying a for loop that iterates over each value. However, when I stack back the copied rows and columns using numpy.vstack() and numpy.hstack(), then everything again converts to strings type. So, not sure why this is happening.

b.除了我使用numpy.insert()方法插入行和列外,其他步骤与a点相同,但是却在做相同的事情-将所有内容都转换回字符串类型.

b. Same procedure as point a, except I used numpy.insert() method for inserting rows and columns, but is doing the same thing - converting everything back to string type.

因此,有没有一种方法可以不必通过这种删除和堆叠机制(无论如何都无法工作),并且可以将数组的所有值(第一行和第一列除外)更改为int()float()类型?

So, is there a way through which I don't have to go through this deleting and stacking mechanism (which isn't working anyways) and I can change all the values (except first row and column) of an array to int() or float() type?

推荐答案

一个numpy数组中的所有项目都必须具有相同的dtype.这是有关numpy的基本事实.您可以使用numpy recarray,也可以使用dtype=object,它基本上使所有值都是任意值.

All items in a numpy array have to have the same dtype. That is a fundamental fact about numpy. You could possibly use a numpy recarray, or you could use dtype=object which basically lets all values be anything.

我建议您看看 pandas ,它提供了表格数据结构,允许不同的列有不同的类型.听起来您所拥有的是一张带有行和列标签的表,而这正是熊猫很好地处理的.

I'd recommend you take a look at pandas, which provides a tabular data structure that allows different columns to have different types. It sounds like what you have is a table with row and column labels, and that's what pandas deals with nicely.

这篇关于更改numpy数组中特定值的dtype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆