简体   繁体   English

从python numpy数组写入逗号分隔的值

[英]Write comma separated values from python numpy array

I'm creating a custom file writer. 我正在创建一个自定义文件编写器。 I need to write out the values of my array as comma separated into one line in the file. 我需要写出数组的值,以逗号分隔文件中的一行。 I could do the following: 我可以执行以下操作:

def as_csv(array):

    return ','.join([str(i) for i in array]) + '\n'

then: 然后:

outfile.write(my_header)
outfile.write(other_stuff)
outfile.write(as_csv(array))

but I wonder if this is the most efficient way to do this, or if there would be a better method using the numpy.array_str or numpy.array_repr methods. 但我想知道这是否是最有效的方法,或者使用numpy.array_str或numpy.array_repr方法是否会有更好的方法。

您还可以使用内置的numpy方法np.savetxthttp : np.savetxt

np.savetxt(outfile, array, delimiter=',')

I haven't tried to use np.savetxt in the context below, perhaps it could be used so long as the file is opened in append mode, but here is the solution for what I was trying to do. 我没有尝试在下面的上下文中使用np.savetxt ,也许只要在附加模式下打开文件就可以使用它,但这是我尝试做的解决方案。 However, it may not be the most efficient.. 但是,它可能不是最有效的。

def _as_csv(self, values):
    vals = ','.join([str(i) for i in values])
    return vals + '\n'

def output(self, filename, series_cnt, series_name, series_type, startdate, N, values, step = 1000):
    """ outputs data to a file """

    starttime = startdate

    num_imports = (N / step) + 1

    outfile = open(filename.format(series_cnt, i), 'w')
    outfile.write('#{0},{1},{2},\n'.format('TEST', startdate.strftime('%Y%m%d%H%M%S000'), str(num_imports)))


    for i in range(0, N, step):

        line_start = '/Test/{0},{1},{2},{3},'.format(series_name, series_type, starttime.strftime('%Y%m%d%H%M%S000'), step)
        outfile.write(line_start)
        nxt = i + step
        starttime = starttime + dt.timedelta(hours=step)

        outfile.write(self._as_csv(values[i:nxt]))

        outfile.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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