Dump a NumPy array into a csv file

前端 未结 10 1321

Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format.

10条回答
  •  半阙折子戏
    2020-11-22 13:29

    Writing record arrays as CSV files with headers requires a bit more work.

    This example reads from a CSV file ('example.csv') and writes its contents to another CSV file (out.csv).

    import numpy as np
    
    # Write an example CSV file with headers on first line
    with open('example.csv', 'w') as fp:
        fp.write('''\
    col1,col2,col3
    1,100.1,string1
    2,222.2,second string
    ''')
    
    # Read it as a Numpy record array
    ar = np.recfromcsv('example.csv')
    print(repr(ar))
    # rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')], 
    #           dtype=[('col1', '

    Note that the above example cannot handle values which are strings with commas. To always enclose non-numeric values within quotes, use the csv package:

    import csv
    
    with open('out2.csv', 'wb') as fp:
        writer = csv.writer(fp, quoting=csv.QUOTE_NONNUMERIC)
        writer.writerow(ar.dtype.names)
        writer.writerows(ar.tolist())
    

提交回复
热议问题