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


当前回答

要将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')

其他回答

如果你想保存你的numpy数组(例如your_array = np.array([[1,2],[3,4]]))到一个单元格,你可以先用your_array.tolist()转换它。

然后以正常的方式保存到一个单元格,分隔符=';' csv-file中的单元格看起来像这样[[1,2],[2,4]]

然后你可以像这样恢复你的数组: Your_array = np.array(ast.literal_eval(cell_string))

将记录数组写入带标题的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数组转换为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

你也可以在不使用任何模块的情况下使用纯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)

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

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