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


当前回答

将记录数组写入带标题的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())

其他回答

你也可以在不使用任何模块的情况下使用纯python来实现。

# format as a block of csv text to do whatever you want
csv_rows = ["{},{}".format(i, j) for i, j in array]
csv_text = "\n".join(csv_rows)

# write it to a file
with open('file.csv', 'w') as f:
    f.write(csv_text)

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

NumPy .savetxt()方法用于将NumPy数组保存到输出文本文件中,但是默认情况下它将使用科学表示法。


如果希望避免这种情况,则需要使用fmt参数指定适当的格式。例如,

import numpy as np

np.savetxt('output.csv', arr, delimiter=',', fmt='%f')

将记录数组写入带标题的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())