Dump a NumPy array into a csv file
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.
numpy.savetxt
将数组保存到文本文件。
import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")
用熊猫轻松快捷
import pandas as pd
df = pd.DataFrame(np_array)
df.to_csv("file_path.csv")
tofile
is a convenient function to do this:
import numpy as np
a = np.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
a.tofile('foo.csv',sep=',',format='%10.5f')
The man page has some useful notes:
This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.
Note. This function does not produce multi-line csv files, it saves everything to one line.
链接地址: http://www.djcxy.com/p/48366.html上一篇: 3D数组中每个元素的Numpy索引值
下一篇: 将NumPy数组转储到csv文件中