如何将NumPy数组转储为人类可读格式的csv文件?


当前回答

在Python中,我们使用csv.writer()模块将数据写入csv文件。这个模块类似于csv.reader()模块。

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()

分隔符是用来分隔字段的字符串。默认值为“,”。

其他回答

要将NumPy数组存储到文本文件中,请从NumPy模块导入savetxt

假设你的Numpy数组名称是train_df:

import numpy as np
np.savetxt('train_df.txt', train_df, fmt='%s')

OR

from numpy import savetxt
savetxt('train_df.txt', train_df, fmt='%s')

在Python中,我们使用csv.writer()模块将数据写入csv文件。这个模块类似于csv.reader()模块。

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()

分隔符是用来分隔字段的字符串。默认值为“,”。

将记录数组写入带标题的CSV文件需要更多的工作。

这个例子从一个CSV文件(example. CSV)中读取,并将其内容写入另一个CSV文件(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', encoding='ascii')
print(repr(ar))
# rec.array([(1, 100.1, 'string1'), (2, 222.2, 'second string')], 
#           dtype=[('col1', '<i8'), ('col2', '<f8'), ('col3', '<U13')])

# Write as a CSV file with headers on first line
with open('out.csv', 'w') as fp:
    fp.write(','.join(ar.dtype.names) + '\n')
    np.savetxt(fp, ar, '%s', ',')

注意,上面的例子不能处理带有逗号的字符串的值。要始终将非数字值括在引号内,请使用csv内置模块:

import csv

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

numpy。Savetxt将数组保存到文本文件中。

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

我相信你也可以很简单地做到以下几点:

将Numpy数组转换为Pandas数据框架 另存为CSV

例如# 1:

    # Libraries to import
    import pandas as pd
    import nump as np

    #N x N numpy array (dimensions dont matter)
    corr_mat    #your numpy array
    my_df = pd.DataFrame(corr_mat)  #converting it to a pandas dataframe

例如# 2:

    #save as csv 
    my_df.to_csv('foo.csv', index=False)   # "foo" is the name you want to give
                                           # to csv file. Make sure to add ".csv"
                                           # after whatever name like in the code