Fastest way to generate delimited string from 1d numpy array

前端 未结 7 2213
春和景丽
春和景丽 2020-12-15 16:53

I have a program which needs to turn many large one-dimensional numpy arrays of floats into delimited strings. I am finding this operation quite slow relative to the mathema

7条回答
  •  情歌与酒
    2020-12-15 17:20

    numpy.savetxt is even slower than string.join. ndarray.tofile() doesn't seem to work with StringIO.

    But I do find a faster method (at least applying to OP's example on python2.5 with lower version of numpy):

    import numpy as np
    x = np.random.randn(100000)
    for i in range(100):
        (",%f"*100000)[1:] % tuple(x)
    

    It looks like string format is faster than string join if you have a well defined format such as in this particular case. But I wonder why OP needs such a long string of floating numbers in memory.

    Newer versions of numpy shows no speed improvement.

提交回复
热议问题