python numpy:更改numpy矩阵的列类型 [英] python numpy: Change the column type of a numpy matrix

查看:30
本文介绍了python numpy:更改numpy矩阵的列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

X[:, 1].astype('str')打印(类型(X[0, 1]))

但我得到了以下结果:

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

解决方案

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

<预><代码>>>>a = np.array([[1,2,3],[4,5,6]])数组([[1, 2, 3],[4, 5, 6]])>>>[:,1]数组([2, 5])>>>a[:,1].astype('str') # 这会生成副本然后进行转换.数组(['2', '5'], dtype='<U21')>>>a # 所以原来的数组没有改变.数组([[1, 2, 3],[4, 5, 6]])

I have a numpy matrix X, and I tried to change the datatype of column 1 using the code below:

X[:, 1].astype('str')
print(type(X[0, 1]))

but I got the following result:

<type 'numpy.float64'>

Anyone know why the type was not changed to str ? And what is a correct way to change the column type of X?Thanks!

解决方案

Providing a simple example will explain it better.

>>> 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]])

这篇关于python numpy:更改numpy矩阵的列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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