如何将 ndarray 的指定元素转换为具体类型

How to convert specified elements of the ndarray to the concrete type

我必须在不使用 pandas 或其他东西的情况下做到这一点,只是纯粹的 numpy

我从 CSV 文件中读取了 ndarraynumpy.str_,我想将每个 的每个元素转换为特定的类型。例如,我知道在第二列中会有一个整数,我想将第一列的所有元素转换为 numpy.float,将第二列的每个元素转换为 numpy.int 等等,有没有办法优雅地实现它?

+当我使用 np.array()list 转换为 ndarray 时,有没有办法指定应将哪些元素转换为哪种类型,以某种方式玩 dtype?

我试图找到一些东西并找到了这个 https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays 但我认为这不是我要找的东西。如果是,可以解释一下如何在我的情况下使用它。

感谢您的帮助。

示例:

我有[['1', '1.6', 'hey']['2', '5', 'tr5']]

我怎样才能得到像

这样的东西

array([1, 1.6, 'hey'][2, 5.0, 'tr5'])

是的,结构化数组正是您所需要的。

您必须按如下方式传递 dtype 参数:

np.array(data, dtype=[(name1, type1), (name2, type2), ...])

其中数据是包含字段的元组列表。

您必须将原始数组转换为该结构。

如果您不需要名称,只需输入空字符串即可。

你也可以将 dtype 参数设置为 dtype=np.dtype(type1, type2,...)