如何直接将COO格式字符串转换为NumPy矩阵?
直接将COO格式字符串转换为NumPy矩阵的方法
你可以利用Python的io.StringIO模块把字符串模拟成文件对象,这样就能直接用np.loadtxt读取,无需写入实际文件。修改后的代码如下:
from scipy.sparse import coo_matrix import numpy as np from io import StringIO # 你的COO格式字符串 matrix_str = """0 0 -1627.761282 0 1 342.811259 0 2 342.811259 0 3 171.372276 0 4 342.744553 0 5 342.744553""" # 使用StringIO模拟文件对象 text = np.loadtxt(StringIO(matrix_str), delimiter=' ') rows, cols, data = text.T matrix = coo_matrix((data, (rows.astype(int), cols.astype(int)))).todense()
或者,你也可以直接用np.fromstring将字符串解析为一维数组,再重塑成3列的矩阵,步骤更简洁:
from scipy.sparse import coo_matrix import numpy as np matrix_str = """0 0 -1627.761282 0 1 342.811259 0 2 342.811259 0 3 171.372276 0 4 342.744553 0 5 342.744553""" # 解析字符串为数组并重塑形状 arr = np.fromstring(matrix_str, sep=' ').reshape(-1, 3) rows, cols, data = arr.T matrix = coo_matrix((data, (rows.astype(int), cols.astype(int)))).todense()
两种方法都能跳过文件写入步骤,直接处理字符串生成矩阵。第一种方法和你原有代码逻辑更接近,第二种则更高效,省去了模拟文件的开销。
内容的提问来源于stack exchange,提问作者voxter
相关产品推荐
相关产品推荐

