numpy中loadtxt 的用法详解
作者:ChangChun_He 时间:2022-03-21 09:46:39
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
来源:https://www.cnblogs.com/hecc/p/8480532.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python函数中return后的语句一定不会执行吗?
Python轻量级web框架bottle使用方法解析
修改、删除数据记录(DELETE\\UPDATE)
九宫格基本布局
![](https://img.aspxhome.com/file/UploadPic/20096/18/01-34s.gif)
Javascript学习第一季 二
对numpy中shape的深入理解
python定时截屏实现
![](https://img.aspxhome.com/file/2023/6/86206_0s.jpg)
Python实现判断给定列表是否有重复元素的方法
![](https://img.aspxhome.com/file/2023/1/93551_0s.png)
Python画图小案例之小雪人超详细源码注释
讲解Python中运算符使用时的优先级
![](https://img.aspxhome.com/file/2023/2/92382_0s.jpg)
Web UI 设计(网页设计)命名规范
![](https://img.aspxhome.com/file/UploadPic/20095/13/web-ui-design-title1-57s.jpg)
Python实现人脸识别
![](https://img.aspxhome.com/file/2023/9/80809_0s.png)
巧用Dreamweaver MX共享Execl XP文件
python装饰器相当于函数的调用方式
Python的Flask框架中@app.route的用法教程
python3实现163邮箱SMTP发送邮件
![](https://img.aspxhome.com/file/2023/8/63538_0s.jpg)
Firefox Bug: inline/inline-block的间隙
python 实现list或string按指定分段
火车票抢票python代码公开揭秘!
![](https://img.aspxhome.com/file/2023/1/93571_0s.jpg)