一、保存csv文件
1.1np.savetxt()函数讲解
np.savetxt(frame, array, fmt='%.18e', delimiter=None)
* frame : 文件、字符串或产生器,可以是.gz或.bz2的压缩文件
* array : 存入文件的数组
* fmt : 写入文件的格式,例如:%d %.2f %.18e
* delimiter : 分割字符串,默认是任何空格
1.2案例实操
import numpy as np
scores=np.random.randint(0,100,size=(20,2))
#执行命令之前,这个保存到文件要关闭
np.savetxt("scores2.csv",scores,delimiter=",",header='英语,数学',comments="")
# 保存文件的名字 保存的数组名 分割符 表的头部,与分隔符一致 注释默认是#
np.savetxt("scores3.csv",scores,delimiter=",",header='英语,数学',comments="",fmt='%d')
#保存数据的格式默认是科学计数法,这里我们改成整型
1.3函数介绍help(np.savetxt)
Help on function savetxt in module numpy.lib.npyio:
savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Save an array to a text file.
Parameters
----------
fname : filename or file handle
If the filename ends in ``.gz``, the file is automatically saved in
compressed gzip format. `loadtxt` understands gzipped files
transparently.
X : 1D or 2D array_like
Data to be saved to a text file.
fmt : str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a
multi-format string, e.g. 'Iteration %d -- %10.5f', in which
case `delimiter` is ignored. For complex `X`, the legal options
for `fmt` are:
* a single specifier, `fmt='%.4e'`, resulting in numbers formatted
like `' (%s+%sj)' % (fmt, fmt)`
* a full string specifying every real and imaginary part, e.g.
`' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
* a list of specifiers, one per column - in this case, the real
and imaginary part must have separate specifiers,
e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
delimiter : str, optional
String or character separating columns.