python 矩阵类型转换_Python 矩阵与字符串转换问题
日期: 2020-11-25 分类: 个人收藏 386次阅读
矩阵 && 字符串转换问题
一、创建一个矩阵
借助np.array 函数创建一个新的矩阵
import numpy as np
Da = [[1,2],[2,3],[2,6]]
print(type(Da))
D = np.array(Da)
print(type(D))
print(D)
[[1 2]
[2 3]
[2 6]]
二、将矩阵转化为字符串
(1)如果按照字典等常规转思路
利用str、及np.array将来回转化矩阵与字符串
虽然也可以转换,会丧失矩阵的维度等信息
实例
创建一个矩阵,维度为(3,2)
#创建一个矩阵,维度为(3,2)
D = np.array([[1,2],[2,3],[2,6]])
print(D)
print(type(D))
print(D.shape)
[[1 2]
[2 3]
[2 6]]
(3, 2)
利用str将其转换为字符串,再将其转化为矩阵
#利用str将其转换为字符串
DD = str(D)
print(type(DD))
#将其转化为矩阵
D = np.array(DD)
print(D)
print(type(D))
print(D.shape) #维度
print(D.size) #纵行
print(D.ndim) #维度
[[1 2]
[2 3]
[2 6]]
()
1
0
从中可以看见原本维度信息为(3,2)的矩阵在经过转换后,维度信息不再存在。
同时利用reshape函数也不可以恢复原有行列信息
(2)tostring && fromstring 方法
tostring :将矩阵转化为字符串
fromstring:将字符串再转化为矩阵,可以规定转化类型
实例
a = np.random.rand(3,4)
b = a.tostring() #转换为字符串
c = np.fromstring(b,dtype=float) #转换为矩阵
#c = np.frombuffer(b,dtype=int)
#输出
print('输出A:')
print(type(a))
print(a.shape)
print(a)
print('输出B:')
print(type(b))
print(b)
print('输出C:')
print(type(c))
print(c.shape)
print(c)
输出A:
D:/python/python_project/tttt2.py:25: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
(3, 4)
c = np.fromstring(b,dtype=float)
[[0.25979539 0.49373422 0.76436538 0.48422897]
[0.68051862 0.54238082 0.19447206 0.6598662 ]
[0.21762024 0.35952261 0.36893753 0.67214753]]
输出B:
b'\xda\xa0k\xd6|\xa0\xd0?\xee\x88?nW\x99\xdf?H\xf1\x16c\xaeu\xe8?(^\xfd\x80\x9b\xfd\xde?\xf0\xf9L\xfd\xce\xc6\xe5?\x05!\xc7\x07/[\xe1?\xf4\xc3\x90\xdeu\xe4\xc8?\x83 H\xb7\x9f\x1d\xe5?\xbc,\xb0\xec\xfa\xda\xcb?\xd8Z#\x1ak\x02\xd7?F/-+\xac\x9c\xd7?r\x9f[\x8b;\x82\xe5?'
输出C:
(12,)
[0.25979539 0.49373422 0.76436538 0.48422897 0.68051862 0.54238082
0.19447206 0.6598662 0.21762024 0.35952261 0.36893753 0.67214753]
可以看出来同样,把矩阵原来的(3,4)重新(12,)12行,损失了维度信息
但是利用reshape(行,列)重新恢复维度信息
d = c.reshape(3,4)
print(type(d))
print(d.shape)
print(d)
(3, 4)
[[0.3740874 0.73670932 0.09303188 0.90885946]
[0.58919281 0.99866281 0.25989112 0.13196649]
[0.29419546 0.20757116 0.77350951 0.65042576]]
所以合并完善一下函数 fromstring 函数
c = np.fromstring(b,dtype=float).reshape(3,4)
(3)sub的方法
sub的语法:
re.sub(pattern, repl, string, count=0, flags=0)
pattern:模式字符串,待匹配
repl:被替换的字符串
string :待处理的string字符串
count:假如对于匹配到的内容,只处理其中一部分
import numpy as np
import re
a = np.random.rand(3,4)
y = str(a)
y = re.sub('\\[', '', y)
y = re.sub('\\]', '', y)
m = np.array(y.split()).reshape(3, 4)
print('输出y:')
print(type(y))
print(y)
print('输出m:')
print(type(m))
print(m.shape)
print(m)
输出y:
0.21022466 0.75059866 0.47868066 0.92805292
0.55057062 0.49618457 0.12894694 0.66451019
0.41080918 0.64166386 0.28036787 0.96659884
输出m:
(3, 4)
[['0.21022466' '0.75059866' '0.47868066' '0.92805292']
['0.55057062' '0.49618457' '0.12894694' '0.66451019']
['0.41080918' '0.64166386' '0.28036787' '0.96659884']]
原文链接:https://blog.csdn.net/amamalll
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
精华推荐