Skip to content Skip to sidebar Skip to footer

What Is The Most Efficient Way To Get This Kind Of Matrix From A 1d Numpy Array?

I have a file with total 4950 values like: 0.012345678912345678 I read the file using: a = numpy.genfromtxt(file_name, dtype=str, delimiter=',') # a.shape = (4950L, 1L) #dtype=str

Solution 1:

Not sure if it is the most efficient way, but this seems pretty efficient.

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

Post a Comment for "What Is The Most Efficient Way To Get This Kind Of Matrix From A 1d Numpy Array?"