脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - numpy中loadtxt 的用法详解

numpy中loadtxt 的用法详解

2021-03-26 00:09ChangChun_He Python

这篇文章主要介绍了numpy中loadtxt 的用法详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

numpy中有两个函数可以用来读取文件,主要是txt文件, 下面主要来介绍这两个函数的用法

第一个是loadtxt, 其一般用法为

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

上面给出了loadtxt所有的关键字参数, 这里我们可以来一一解释并给出示例

这里我们使用的是jupyter notebook, 可以实现交互式的界面操作

?
1
2
3
4
5
%%writefile test.txt # 这是用来写入文件的代码
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

首先给出最简单的loadtxt的代码

?
1
2
3
import numpy as np
a = np.loadtxt('test.txt')#最普通的loadtxt
print(a)

实际上就是直接写文件名, 其他关键字参数都是默认的。输出为

[[1. 2. 3. 4.]
 [2. 3. 4. 5.]
 [3. 4. 5. 6.]
 [4. 5. 6. 7.]]

a为浮点数的原因为Python默认的数字的数据类型为双精度浮点数

?
1
2
3
4
5
6
7
8
%%writefile test.txt
A B C
1 2 3
4 5 6
7 8 9
 
a = np.loadtxt('test1.txt', skiprows=1, dtype=int)
print(a)

这里的skiprows是指跳过前1行, 如果设置skiprows=2, 就会跳过前两行,  这里的输出为

[[1 2 3]
 [4 5 6]
 [7 8 9]]

?
1
2
3
4
5
6
7
8
9
%%writefile test.txt
A B C
1 2 3
# AAA
4 5 6
7 8 9
 
a = np.loadtxt('test2.txt', dtype=int, skiprows=1, comments='#')
print(a)

这里的comment的是指, 如果行的开头为#就会跳过该行, 这里输出为

[[1 2 3]
 [4 5 6]
 [7 8 9]]

?
1
2
3
4
5
6
7
8
9
%%writefile test.txt
A B C
1, 2, 3
# AA AAA
4, 5, 6
7, 8, 9
 
(a, b) = np.loadtxt('test.txt', dtype=int, skiprows=1, comments='#', delimiter=',', usecols=(0, 2), unpack=True)
print(a, b)

这里的usecols是指只使用0,2两列, unpack是指会把每一列当成一个向量输出, 而不是合并在一起。

[1 4 7] [3 6 9]

最后介绍converters参数, 这个是对数据进行预处理的参数, 我们可以先定义一个函数, 这里的converters是一个字典, 表示第零列使用函数add_one来进行预处理

?
1
2
3
4
def add_one(x):
return int(x)+1#注意到这里使用的字符的数据结构
(a, b) = np.loadtxt('test.txt', dtype=int, skiprows=1, converters={0:add_one}, comments='#', delimiter=',', usecols=(0, 2), unpack=True)
print(a, b)

输出结果为:

[2 5 8] [3 6 9]

补一个GitHub的jupyter-notebook链接...

https://github.com/ChangChunHe/PythonLearning/blob/master/Numpy/8.loadtxt_and_genfromtxt.ipynb

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/hecc/p/8480532.html

延伸 · 阅读

精彩推荐