繁体   English   中英

从一维numpy数组中获取这种矩阵的最有效方法是什么?

[英]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

  1. 上三角值由numpy数组'a'中的值填充。
  2. 下三角值由numpy数组'a'中的值填充,但乘以-1。
  3. 对角线仅包含零。

示例(精度很重要):

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM