python怎么将numpy array string类转为string类

人生苦短,我用Python
这篇文章我们玩玩numpy的数值数据类型转换
&&& import numpy as np
一、随便玩玩
生成一个浮点数组
&&& a = np.random.random(4)
array([ 0.0945377 ,
&&& a.dtype
dtype('float64')
&&& a.shape
改变dtype,发现数组长度翻倍!
&&& a.dtype = 'float32'
1.], dtype=float32)
&&& a.shape
改变dtype,数组长度再次翻倍!
&&& a.dtype = 'float16'
array([ -9.,
1.], dtype=float16)
&&& a.shape
改变dtype='float',发现默认就是float64,长度也变回最初的4
&&& a.dtype = 'float'
array([ 0.0945377 ,
&&& a.shape
&&& a.dtype
dtype('float64')
把a变为整数,观察其信息
&&& a.dtype = 'int64'
array([91,
8854048], dtype=int64)
&&& a.shape
改变dtype,发现数组长度翻倍!
&&& a.dtype = 'int32'
&&& a.shape
改变dtype,发现数组长度再次翻倍!
&&& a.dtype = 'int16'
array([-31160,
32432, -26931, -19401,
-17331, -10374,
16355, -20192, -24589,
16331], dtype=int16)
&&& a.shape
改变dtype,发现数组长度再次翻倍!
&&& a.dtype = 'int8'
-97, -124,
63], dtype=int8)
&&& a.shape
改变dtype,发现整数默认int32!
&&& a.dtype = 'int'
&&& a.dtype
dtype('int32')
&&& a.shape
二、换一种玩法
很多时候我们用numpy从文本文件读取数据作为numpy的数组,默认的dtype是float64。但是有些场合我们希望有些数据列作为整数。如果直接改dtype='int'的话,就会出错!原因如上,数组长度翻倍了!!!
下面的场景假设我们得到了导入的数据。我们的本意是希望它们是整数,但实际上是却是浮点数(float64)
&&& b = np.array([1., 2., 3., 4.])
&&& b.dtype
dtype('float64')
用 astype(int) 得到整数,并且不改变数组长度
&&& c = b.astype(int)
array([1, 2, 3, 4])&&& c.shape(8,)
&&& c.dtype
dtype('int32')
如果直接改变b的dtype的话,b的长度翻倍了,这不是我们想要的(当然如果你想的话)
array([ 1.,
&&& b.dtype = 'int'
&&& b.dtype
dtype('int32')
&&& b.shape
numpy中的数据类型转换,不能直接改原数据的dtype!& 只能用函数astype()。
阅读(...) 评论()1.函数的定义与说明
  函数格式tile(A,reps)
  A和reps都是array_like
  A的类型众多,几乎所有类型都可以:array, list, tuple, dict, matrix以及基本数据类型int, string, float以及bool类型。
  reps的类型也很多,可以是tuple,list, dict, array, int, bool.但不可以是float, string, matrix类型。
2.函数操作示例
&&& tile(1,2)
array([1, 1])
&&& tile((1,2,3),3)
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
&&& tile(a,2)
array([[1, 2, 3, 1, 2, 3],
[4, 5, 5, 4, 5, 5]])
&&& b=[1,3,5]
&&& tile(b,[2,3])
array([[1, 3, 5, 1, 3, 5, 1, 3, 5],
[1, 3, 5, 1, 3, 5, 1, 3, 5]])
&&& a=[[1,2,3],[5,4]]
&&& tile(a,[2,3])
array([[[1, 2, 3], [5, 4], [1, 2, 3], [5, 4], [1, 2, 3], [5, 4]],
[[1, 2, 3], [5, 4], [1, 2, 3], [5, 4], [1, 2, 3], [5, 4]]])
阅读(...) 评论()numpy数组与python的list互转,其后用json写入文件与c交互 - JavaScript当前位置:& &&&numpy数组与python的list互转,其后用json写入文件numpy数组与python的list互转,其后用json写入文件与c交互&&网友分享于:&&浏览:120次numpy数组与python的list互转,然后用json写入文件与c交互
1.对于numpy的tofile方法,一个一维数组可以直接写成二进制形式,用c语言或者numpy.fromfile()可以读出来内容。而如果数组超过一维,tofile并不区分,也就是arr1=[1,2,3,4],arr2=[[1,2],[3,4]]写入文件是一样的
2.对于json写入numpy数组的想法,已知json只能写入python的数组,而不认识numpy的。难点在于如何将json的数组转化为python的,尽管反过来转换很容易,而且数组的最外围可以通过list方法转成python。但是里面的格式仍然是numpy的,这样json还是不能使用。我觉得很蛋疼,为什么反过来就没有接口?我找不到啊。。。
3.就在刚才突然找到了ndarray.tolist()可以将numpy的数组转为python的list,哈哈哈。现在可以用json写入numpy的数组,剩下的研究一下cpp如何使用json读取就行了,也就是jsoncpp貌似。
弄了一天啊,就找了几个接口,还好找到了。
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有}

我要回帖

更多关于 python 转为string 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信