numpy教程:基本输入输出和文件输入输出Input and output

http://blog.csdn.net/pipisorry/article/details/39088003 

基本输入输出和文件输入输出

文件名和文件对象

本节介绍所举的例子都是传递的文件名,也可以传递已经打开的文件对象.

例如对于load和save函数来说,如果使用文件对象的话,可以将多个数组储存到一个npy文件中:

>>> a = np.arange(8)
>>> b = np.add.accumulate(a)
>>> c = a + b
>>> f = file("result.npy", "wb")
>>> np.save(f, a) # 顺序将a,b,c保存进文件对象f
>>> np.save(f, b)
>>> np.save(f, c)
>>> f.close()
>>> f = file("result.npy", "rb")
>>> np.load(f) # 顺序从文件对象f中读取内容
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.load(f)
array([ 0,  1,  3,  6, 10, 15, 21, 28])
>>> np.load(f)
array([ 0,  2,  5,  9, 14, 20, 27, 35])

文件对象写入时的注意事项

numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=’‘, footer=’‘, comments=’#‘)
Save an array to a text file.

np.savetxt(输出文件名,矩阵名)

输出文件名应为二进制写入:

doc_word_mat_file = open('./filename.txt', 'wb')

否则出错:

    savetxt(doc_word_mat_file, doc_word_mat) ...     fh.write(asbytes(format % tuple(row) + newline))
TypeError: must be str, not bytes

所以推荐不要使用文件对象写入,用文件名写入

皮皮blog

numpy数组输出选项设置

在屏幕上输出数组:print(mat1)

Text formatting options

set_printoptions([precision, threshold, ...])Set printing options.
get_printoptions()Return the current print options.
set_string_function(f[, repr])Set a Python function to be used when pretty printing arrays.

numpy数组打印效果设置

np.set_printoptions(precision=5, suppress=True, threshold=np.inf, formatter={'float': '{: 0.3f}'.format}, linewidth=120)

使用precision设置输出精度

np.set_printoptions(precision=3)
print(x)
# [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]

但是怎么没办法输出原本数据的最精确精度,如有的数据是10位小数,有的是8位,输出不好控制precision为多少好。精度过高就会出错。

这时可以使用array.astype(str)转换成字符串输出。如

[['40.731354990929475' '-74.00363118575608']
  ['40.731508' '-74.0031859561163']]

suppress禁用科学记数法

y=np.array([1.5e-10,1.5,1500])
print(y)
# [  1.500e-10   1.500e+00   1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [    0.      1.5  1500. ]

在本地应用打印选项 中, 你可以使用 contextmanager ...

formatter参数允许你指定一个格式为每个类型的函数(注意结尾补0了)

np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)

[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]

奇怪的方式
print(np.char.mod('%4.2f', eigen_value))

[Pretty-printing of numpy.array][numpy.array的效果]

threshold多维数组强制打印全部输出

如果一个数组用来打印太大了,NumPy自动省略中间部分而只打印角落。禁用NumPy的这种行为并强制打印整个数组,你可以设置printoptions参数来更改打印选项。

np.set_printoptions(threshold=np.inf)

threshold : int, optional   Total number of array elements which trigger summarizationrather than full repr (default 1000).

linewidth“大”矩阵输出

“大”矩阵输出时,Pycharm console自动添加换行符

PyCharm默认控制台宽度设置为80个字符。


np.set_printoptions(linewidth=120) 

对于pandas:
pd.set_option('display.width', 120)

numpy输出局部控制

@contextmanager
def np_printoptions(*args, **kwargs):
    '''
    numpy本地应用打印选项,如:
    with np_printoptions(precision=3, suppress=True):
        print(x1)
    '''
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    yield
    np.set_printoptions(**original)

皮皮blog

numpy文件存取

NumPy提供了多种文件操作函数方便我们存取数组内容。

文件存取的格式:二进制和文本。二进制格式的文件又分为NumPy专用的格式化二进制类型和无格式类型。

Numpy binary files (NPY, NPZ)

load(file[, mmap_mode, allow_pickle, ...])Load arrays or pickled objects from .npy, .npz or pickled files.
save(file, arr[, allow_pickle, fix_imports])Save an array to a binary file in NumPy .npy format.
savez(file, *args, **kwds)Save several arrays into a single file in uncompressed .npz format.
savez_compressed(file, *args, **kwds)Save several arrays into a single file in compressed .npz format.

The format of these binary file types is documented inhttp://docs.scipy.org/doc/numpy/neps/npy-format.html

numpy.load和numpy.save函数(推荐在不需要查看保存数据的情况下使用)

以NumPy专用的二进制类型保存数据,这两个函数会自动处理元素类型和shape等信息,使用它们读写数组就方便多了,但是numpy.save输出的文件很难和其它语言编写的程序读入:

>>> np.save("a.npy", a)
>>> c = np.load( "a.npy" )
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Note:

1. 文件要保存为.npy文件类型,否则会出错

2. 保存为numpy专用二进制格式后,就不能用notepad++打开(乱码)看了,这是相对tofile内建函数不好的一点

numpy.savez函数

如果你想将多个数组保存到一个文件中的话,可以使用numpy.savez函数。savez函数的第一个参数是文件名,其后的参数都是需要保存的数组,也可以使用关键字参数为数组起一个名字,非关键字参数传递的数组会自动起名为arr_0, arr_1, ...。savez函数输出的是一个压缩文件(扩展名为npz),其中每个文件都是一个save函数保存的npy文件,文件名对应于数组名。load函数自动识别npz文件,并且返回一个类似于字典的对象,可以通过数组名作为关键字获取数组的内容:

>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.arange(0, 1.0, 0.1)
>>> c = np.sin(b)
>>> np.savez("result.npz", a, b, sin_array = c)
>>> r = np.load("result.npz")
>>> r["arr_0"] # 数组a
array([[1, 2, 3],
       [4, 5, 6]])
>>> r["arr_1"] # 数组b
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])
>>> r["sin_array"] # 数组c
array([ 0.        ,  0.09983342,  0.19866933,  0.29552021,  0.38941834,
        0.47942554,  0.56464247,  0.64421769,  0.71735609,  0.78332691])

如果你用解压软件打开result.npz文件的话,会发现其中有三个文件:arr_0.npy, arr_1.npy, sin_array.npy,其中分别保存着数组a, b, c的内容。

皮皮blog

numpy读取文本文件Text files

loadtxt(fname[, dtype, comments, delimiter, ...])Load data from a text file.
savetxt(fname, X[, fmt, delimiter, newline, ...])Save an array to a text file.
genfromtxt(fname[, dtype, comments, ...])Load data from a text file, with missing values handled as specified.
fromregex(file, regexp, dtype)Construct an array from a text file, using regular expression parsing.
fromstring(string[, dtype, count, sep])A new 1-D array initialized from raw binary or text data in a string.
ndarray.tofile(fid[, sep, format])Write array to a file as text or binary (default).
ndarray.tolist()Return the array as a (possibly nested) list.

numpy.savetxt和numpy.loadtxt(推荐需要查看保存数据时使用)

使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组:

np.loadtxt(FILENAME, dtype=int, delimiter=' ')

numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)

使用结构数组读入文件
persontype = np.dtype({'names':['name', 'age', 'weight', 'height'],
                       'formats':['S32','i', 'f', 'f']})
data = np.loadtxt(f, delimiter=",", dtype=persontype)

np.savetxt("a.txt",a, fmt="%d",delimiter=",")

>>> a = np.arange(0,12,0.5).reshape(4,-1)
>>> np.savetxt("a.txt", a) # 缺省按照'%.18e'格式保存数据,以空格分隔
>>> np.loadtxt("a.txt")

>>> np.savetxt("a.txt", a, fmt="%d", delimiter=",") #改为保存为整数,以逗号分隔
>>> np.loadtxt("a.txt",delimiter=",") # 读入的时候也需要指定逗号分隔
array([[  0.,   0.,   1.,   1.,   2.,   2.],
       [  3.,   3.,   4.,   4.,   5.,   5.],
       [  6.,   6.,   7.,   7.,   8.,   8.],
       [  9.,   9.,  10.,  10.,  11.,  11.]])

Note:savetxt缺省按照'%.18e'格式保存数据, 可以修改保存格式为‘%.8f'(小数点后保留8位的浮点数), ’%d'(整数)等等

np.savetxt保存list或者ndarray

np.savetxt('nationwide_add.csv', add_list, fmt='%s', encoding='utf-8', delimiter='\t')

可以保存中文,但是其中的None也变成了字符串“None”而不是真的空。所以建议使用pd.DataFrame(add_list).to_csv('nationwide_add.csv', sep='\t', header=False, index=False)

np.savetxt保存中文字符串数组

实际上是不可以的,因为默认是wb格式保存,这样就是保存为bytes,py3中的str又是unicode,这样就算保存下来了,也并看不了保存下来的中文是什么。

如:

s = np.array([['工', '1'], ['q', '1']])
print(s)
s = np.char.encode(s,'utf-8')
np.savetxt('/tmp/1.txt', s, fmt='%s')

文件中只会这样显示:b'\xe5\xb7\xa5' b'1'
b'q' b'1'

所以有中文的话,而且实在想看文件中的内容,只有使用普通保存方法保存了:with open() as f: f.write(lines)什么的。

[Write numpy unicode array to a text file]

loadtxt出错

1 numpy.loadtxt读入的字符串总是bytes格式,总是在前面加了一个b

原因:np.loadtxt and np.genfromtxt operate in byte mode, which is the default string type in Python 2. But Python 3 uses unicode, and marks bytestrings with this b.  numpy.loadtxt中也声明了:Note that generators should return byte strings for Python 3k.

解决:使用numpy.loadtxt从文件读取字符串,最好使用这种方式np.loadtxt(filename, dtype=bytes).astype(str)

['b' character added when using numpy loadtxt]

[numpy.loadtxt]

总结:

载入txt文件:numpy.loadtxt()/numpy.savetxt()

智能导入文本/csv文件:numpy.genfromtxt()/numpy.recfromcsv()

高速,有效率但numpy特有的二进制格式:numpy.save()/numpy.load()

2 ValueError: Wrong number of columns at line 78446

原因是数据问题,可能前面的数据都是3列而78446却是2或4列等等。

查看数据nl data_test6.txt | grep -C 3 78446

numpy.genfromtxt

import numpy as np
np.genfromtxt('filename', dtype= None)
# array([(1, 2.0, 'buckle_my_shoe'), (3, 4.0, 'margery_door')],
#  dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '|S14')])

皮皮blog

Raw binary files

fromfile(file[, dtype, count, sep])Construct an array from data in a text or binary file.
ndarray.tofile(fid[, sep, format])Write array to a file as text or binary (default).

tofile和fromfile数组内建函数(not recommend)

使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据:

>>> a = np.arange(0,12)
>>> a.shape = 3,4
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> a.tofile("a.bin")
>>> b = np.fromfile("a.bin", dtype=np.float) # 按照float类型读入数据
>>> b # 读入的数据是错误的
array([  2.12199579e-314,   6.36598737e-314,   1.06099790e-313,
         1.48539705e-313,   1.90979621e-313,   2.33419537e-313])
>>> a.dtype # 查看a的dtype
dtype('int32')
>>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32类型读入数据
>>> b # 数据是一维的
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> b.shape = 3, 4 # 按照a的shape修改b的shape
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Note:

1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。

2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}

user_item_mat.tofile(user_item_mat_filename, sep=' ')

皮皮blog

String formatting

array2string(a[, max_line_width, precision, ...])Return a string representation of an array.
array_repr(arr[, max_line_width, precision, ...])Return the string representation of an array.
array_str(a[, max_line_width, precision, ...])Return a string representation of the data in an array.

Memory mapping files

memmapCreate a memory-map to an array stored in a binary file on disk.

Base-n representations

binary_repr(num[, width])Return the binary representation of the input number as a string.
base_repr(number[, base, padding])Return a string representation of a number in the given base system.

Data sources

DataSource([destpath])A generic data source file (file, http, ftp, ...).

from:numpy教程:基本输入输出和文件输入输出Input and output_皮皮blog-CSDN博客

ref: [numpy Input and output]

  • 15
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例代码,用于利用ASE和NUMPY分析多个POSCAR结构文件中C原子的分布共同点: ```python import os import numpy as np from ase.io import read from sklearn.cluster import KMeans import matplotlib.pyplot as plt # 输入文件夹路径 input_dir = 'path/to/input/directory' # 输出文件路径 output_file = 'path/to/output/file' # 读取所有POSCAR文件的结构信息 structures = [] for filename in os.listdir(input_dir): if filename.endswith('.POSCAR'): filepath = os.path.join(input_dir, filename) structure = read(filepath, format='vasp') structures.append(structure) # 获取所有结构中的C原子位置信息 c_atom_positions = [] for structure in structures: c_atom_indices = [i for i, atom in enumerate(structure) if atom.symbol == 'C'] c_atom_positions.append(structure.get_positions()[c_atom_indices]) # 对于所有结构中的C原子位置信息,进行k-means聚类分析 kmeans = KMeans(n_clusters=5, random_state=0).fit(np.concatenate(c_atom_positions, axis=0)) cluster_labels = kmeans.labels_ # 统计每个聚类中的结构数目 cluster_counts = [0] * 5 for c in cluster_labels: cluster_counts[c] += 1 # 输出聚类结果和共同点 with open(output_file, 'w') as f: f.write('共有{}个结构文件\n'.format(len(structures))) f.write('共有{}个C原子\n'.format(sum([len(c) for c in c_atom_positions]))) f.write('共有{}个聚类\n'.format(len(set(cluster_labels)))) f.write('聚类结果:\n') for i, c in enumerate(cluster_counts): f.write('聚类{}:{}个结构\n'.format(i+1, c)) f.write('共同点:\n') for i, structure in enumerate(structures): if cluster_labels[i] == max(set(cluster_labels), key=cluster_labels.count): f.write('{}\n'.format(structure.get_chemical_formula())) # 可视化聚类结果 colors = ['r', 'g', 'b', 'y', 'm'] for i in range(len(cluster_labels)): plt.scatter(c_atom_positions[i][:, 0], c_atom_positions[i][:, 1], c=colors[cluster_labels[i]]) plt.title('C原子位置聚类结果') plt.xlabel('x') plt.ylabel('y') plt.show() ``` 上述代码中,使用ASE库读取POSCAR文件,并获取其中的C原子位置信息。然后,使用numpy库将所有C原子位置信息连接到一起,并使用k-means聚类算法进行聚类。输出聚类结果和共同点到输出文件中,最后使用matplotlib库绘制散点图,展示C原子位置的聚类结果。 需要注意的是,上述代码中的聚类算法和参数均为示例,实际应用中需要根据具体情况进行选择和调整。输出文件和可视化图形也可以根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值