python numpy:更改numpy矩阵的列类型

Eda*_*ame 5 python types numpy

我有一个numpy矩阵X,并且尝试使用以下代码更改列1的数据类型:

X[:, 1].astype('str')
print(type(X[0, 1]))
Run Code Online (Sandbox Code Playgroud)

但我得到以下结果:

<type 'numpy.float64'>
Run Code Online (Sandbox Code Playgroud)

有人知道为什么类型没有更改为str吗?更改X列类型的正确方法是什么?谢谢!

Hun*_*Hun 5

提供一个简单的例子会更好地解释它。

>>> a = np.array([[1,2,3],[4,5,6]])
array([[1, 2, 3],
       [4, 5, 6]])
>>> a[:,1]
array([2, 5])
>>> a[:,1].astype('str') # This generates copy and then cast.
array(['2', '5'], dtype='<U21')
>>> a                    # So the original array did not change.
array([[1, 2, 3],
       [4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)

  • 这解释了为什么它不起作用,但没有解释该怎么做。就我而言,我有一列字符串(从 numpy 的角度来看是对象类型)和一个将这些字符串映射到整数的函数,我想用它来将字符串列转换为整数列。 (5认同)