Dump a NumPy array into a csv file

前端 未结 10 1319

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:17

    In Python we use csv.writer() module to write data into csv files. This module is similar to the csv.reader() module.

    import csv
    
    person = [['SN', 'Person', 'DOB'],
    ['1', 'John', '18/1/1997'],
    ['2', 'Marie','19/2/1998'],
    ['3', 'Simon','20/3/1999'],
    ['4', 'Erik', '21/4/2000'],
    ['5', 'Ana', '22/5/2001']]
    
    csv.register_dialect('myDialect',
    delimiter = '|',
    quoting=csv.QUOTE_NONE,
    skipinitialspace=True)
    
    with open('dob.csv', 'w') as f:
        writer = csv.writer(f, dialect='myDialect')
        for row in person:
           writer.writerow(row)
    
    f.close()
    

    A delimiter is a string used to separate fields. The default value is comma(,).

提交回复
热议问题