[英]What is the most efficient way to get this kind of matrix from a 1D numpy array?
我有一个文件,共有4950
值,例如:
0.012345678912345678
我使用以下文件读取文件:
a = numpy.genfromtxt(file_name, dtype=str, delimiter=',') # a.shape = (4950L, 1L) #dtype=str as I don't want to compromise accuracy
#say a == ['0.000000000000000001', -'0.000000000000000002', ...., '0.000000000004950']
我要实现的目标是获得大小为(100L, 100L)
的矩阵b
:
示例(精度很重要):
array = ['1','2','-3','-5','6','-7'] # In reality the data is up to 18 decimal places.
final_matrix = [
['0','1','2','-3'],
['-1',0,'-5','6'],
['-2','5','0','-7'],
['3','-6','7','0']
]
最有效的方法是什么?
不知道这是否是最有效的方法,但这似乎很有效。
import numpy
# create some random data for testing
sz = 100
a = numpy.random.random(sz*sz/2 - sz/2).astype('S50')
# convert back to float for a test on minus signs,
# as it would be done if a is read as string values
amins = numpy.where(a.astype(float) <= 0, "", "-")
# get the values without minus signs
aplus = numpy.char.lstrip(a, "-")
# addup to negated string values
aminus = numpy.char.add(amins, aplus)
# create an empty matrix
m = numpy.zeros(shape=(sz,sz), dtype='S51')
# ids of the upper triangle
u_ids = numpy.triu_indices(sz,1)
# set upper values
m[u_ids] = a
# switch coordinates to set lower values
m[u_ids[1],u_ids[0]] = aminus
# fill diag with zeros
numpy.fill_diagonal(m, numpy.zeros(sz).astype('S51'))
print m
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.