代码改变世界

numpy中loadtxt 的用法

2018-02-27 19:27  ChangChun_He  阅读(60985)  评论(1编辑  收藏  举报

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

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

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

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

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

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

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

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默认的数字的数据类型为双精度浮点数

%%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]]
%%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]]

%%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来进行预处理
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