Python基础学习——Numpy包(6、输入输出)

本文详细介绍了NumPy库中用于处理二进制文件(.npy, .npz)和文本文件(.txt, .csv)的方法,包括save、load、savez、loadtxt、genfromtxt等函数的使用。通过示例展示了如何保存和读取数组,以及处理缺失值和压缩存储。此外,还讨论了set_printoptions函数用于控制数组打印的格式和选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.numpy二进制文件(.npy,.npz)

save()保存

save(file, arr, allow_pickle=True, fix_imports=True):.npy格式将数组保存到二进制文件中。

load()读取

load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII'):.npy.npz或 pickled文件加载数组或pickled对象。

【例】将一个数组保存到一个文件中并读取文件。

import numpy as np

outfile = r'.\test.npy'
np.random.seed(20200619)
x = np.random.uniform(low=0, high=1,size = [3, 5])
np.save(outfile, x)
y = np.load(outfile)
print(y)
# [[0.01123594 0.66790705 0.50212171 0.7230908  0.61668256]
#  [0.00668332 0.1234096  0.96092409 0.67925305 0.38596837]
#  [0.72342998 0.26258324 0.24318845 0.98795012 0.77370715]]

savez()压缩保存

savez(file, *args, **kwds):以未压缩的.npz格式将多个数组保存到单个文件中。

【例】将多个数组保存到一个文件。

import numpy as np

outfile = r'.\test.npz'
x = np.linspace(0, np.pi, 5)
y = np.sin(x)
z = np.cos(x)
np.savez(outfile, x, y, z_d=z)
data = np.load(outfile)
np.set_printoptions(suppress=True)
print(data.files)  
# ['z_d', 'arr_0', 'arr_1']

print(data['arr_0'])
# [0.         0.78539816 1.57079633 2.35619449 3.14159265]

print(data['arr_1'])
# [0.         0.70710678 1.         0.70710678 0.        ]

print(data['z_d'])
# [ 1.          0.70710678  0.         -0.70710678 -1.        ]

用解压软件打开 test.npz 文件,会发现其中有三个文件:arr_0.npy,arr_1.npy,z_d.npy,其中分别保存着数组x,y,z的内容。

2.文本文件

savetxt()保存

savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n',header='', footer='', comments='# ', encoding=None)

fname:文件路径

X:存入文件的数组。

fmt='%.18e':写入文件中每个元素的字符串格式,默认'%.18e'(保留18位小数的浮点数形式)。

delimiter=' ':分割字符串,默认以空格分隔。

loadtxt()读取

loadtxt(fname, dtype=float, comments='#', delimiter=None,
            converters=None, skiprows=0, usecols=None, unpack=False,
            ndmin=0, encoding='bytes', max_rows=None)

fname:文件路径。

dtype=float:数据类型,默认为float。

comments='#': 字符串或字符串组成的列表,默认为'#',表示注释字符集开始的标志。

skiprows=0:跳过多少行,一般跳过第一行表头。

usecols=None:元组(元组内数据为列的数值索引), 用来指定要读取数据的列(第一列为0)。

unpack=False:当加载多列数据时是否需要将数据列进行解耦赋值给不同的变量。

【例】写入和读出TXT文件。

import numpy as np

outfile = r'.\test.txt'
x = np.arange(0, 10).reshape(2, -1)
np.savetxt(outfile, x)
y = np.loadtxt(outfile)
print(y)
# [[0. 1. 2. 3. 4.]
#  [5. 6. 7. 8. 9.]]

 【例】写入和读出CSV文件。

import numpy as np

outfile = r'.\test.csv'
x = np.arange(0, 10, 0.5).reshape(4, -1)
np.savetxt(outfile, x, fmt='%.3f', delimiter=',')
y = np.loadtxt(outfile, delimiter=',')
print(y)
# [[0.  0.5 1.  1.5 2. ]
#  [2.5 3.  3.5 4.  4.5]
#  [5.  5.5 6.  6.5 7. ]
#  [7.5 8.  8.5 9.  9.5]]

 genfromtxt():从文本文件加载数据,并按指定方式处理缺少的值(是面向结构数组和缺失数据处理的。)。

genfromtxt(fname, dtype=float, comments='#', delimiter=None,
               skip_header=0, skip_footer=0, converters=None,
               missing_values=None, filling_values=None, usecols=None,
               names=None, excludelist=None,
               deletechars=''.join(sorted(NameValidator.defaultdeletechars)),
               replace_space='_', autostrip=False, case_sensitive=True,
               defaultfmt="f%i", unpack=None, usemask=False, loose=True,
               invalid_raise=True, max_rows=None, encoding='bytes'):

names=None:设置为True时,程序将把第一行作为列名称。

data.csv文件(不带缺失值)

id,value1,value2,value3
1,123,1.4,23
2,110,0.5,18
3,164,2.1,19

【例】

import numpy as np

outfile = r'.\data.csv'
x = np.loadtxt(outfile, delimiter=',', skiprows=1)
print(x)
# [[  1.  123.    1.4  23. ]
#  [  2.  110.    0.5  18. ]
#  [  3.  164.    2.1  19. ]]

x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2))
print(x)
# [[123.    1.4]
#  [110.    0.5]
#  [164.    2.1]]

val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True)
print(val1)  # [123. 110. 164.]
print(val2)  # [1.4 0.5 2.1]

【例】

import numpy as np

outfile = r'.\data.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
# [(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]

print(type(x))  
# <class 'numpy.ndarray'>

print(x.dtype)
# [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]

print(x['id'])  # [1. 2. 3.]
print(x['value1'])  # [123. 110. 164.]
print(x['value2'])  # [1.4 0.5 2.1]
print(x['value3'])  # [23. 18. 19.]

data1.csv文件(带有缺失值)

id,value1,value2,value3
1,123,1.4,23
2,110,,18
3,,2.1,19

【例】

import numpy as np

outfile = r'.\data1.csv'
x = np.genfromtxt(outfile, delimiter=',', names=True)
print(x)
# [(1., 123., 1.4, 23.) (2., 110., nan, 18.) (3.,  nan, 2.1, 19.)]

print(type(x))  
# <class 'numpy.ndarray'>

print(x.dtype)
# [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]

print(x['id'])  # [1. 2. 3.]
print(x['value1'])  # [123. 110.  nan]
print(x['value2'])  # [1.4 nan 2.1]
print(x['value3'])  # [23. 18. 19.]

3.文本格式 

set_printoptions(precision=None, threshold=None, edgeitems=None,
                     linewidth=None, suppress=None, nanstr=None, infstr=None,
                     formatter=None, sign=None, floatmode=None, **kwarg):
  • set_printoptions()函数:设置打印选项。这些选项决定浮点数、数组和其它NumPy对象的显示方式。
  • precision=8:设置浮点精度,控制输出的小数点个数,默认是8。
  • threshold=1000:概略显示,超过该值则以“…”的形式来表示,默认是1000。
  • linewidth=75:用于确定每行多少字符数后插入换行符,默认为75。
  • suppress=False:当suppress=True,表示小数不需要以科学计数法的形式输出,默认是False。
  • nanstr=nan:浮点非数字的字符串表示形式,默认nan
  • infstr=inf:浮点无穷大的字符串表示形式,默认inf
  • formatter:一个字典,自定义格式化用于显示的数组元素。键为需要格式化的类型,值为格式化的字符串。
    • 'bool'
    • 'int'
    • 'float'
    • 'str' : all other strings
    • 'all' : sets all types
    • ...

【例】

import numpy as np

np.set_printoptions(precision=4)
x = np.array([1.123456789])
print(x)  # [1.1235]

np.set_printoptions(threshold=20)
x = np.arange(50)
print(x)  # [ 0  1  2 ... 47 48 49]

np.set_printoptions(threshold=np.iinfo(np.int).max)
print(x)
# [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#  24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#  48 49]

eps = np.finfo(float).eps
x = np.arange(4.)
x = x ** 2 - (x + eps) ** 2
print(x)  
# [-4.9304e-32 -4.4409e-16  0.0000e+00  0.0000e+00]
np.set_printoptions(suppress=True)
print(x)  # [-0. -0.  0.  0.]

x = np.linspace(0, 10, 10)
print(x)
# [ 0.      1.1111  2.2222  3.3333  4.4444  5.5556  6.6667  7.7778  8.8889
#  10.    ]
np.set_printoptions(precision=2, suppress=True, threshold=5)
print(x)  # [ 0.    1.11  2.22 ...  7.78  8.89 10.  ]

np.set_printoptions(formatter={'all': lambda x: 'int: ' + str(-x)})
x = np.arange(3)
print(x)  # [int: 0 int: -1 int: -2]

np.set_printoptions()  # formatter gets reset
print(x)  # [0 1 2]

【例】恢复默认选项

np.set_printoptions(edgeitems=3, infstr='inf', linewidth=75,
                    nanstr='nan', precision=8, suppress=False, 
                    threshold=1000, formatter=None)

【函数】

def get_printoptions():
  • get_printoptions()函数:获取当前打印选项。

【例】

import numpy as np

x = np.get_printoptions()
print(x)
# {
# 'edgeitems': 3, 
# 'threshold': 1000, 
# 'floatmode': 'maxprec', 
# 'precision': 8, 
# 'suppress': False, 
# 'linewidth': 75, 
# 'nanstr': 'nan', 
# 'infstr': 'inf', 
# 'sign': '-', 
# 'formatter': None, 
# 'legacy': False
# }

引用至Introduction to Numpy,学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值