随笔 - 1762  文章 - 0  评论 - 109  阅读 - 431万

Python中numpy.loadtxt()读取txt文件

来源:https://www.py.cn/jishu/jichu/20407.html

为了方便使用和记忆,有时候我们会把 numpy.loadtxt() 缩写成np.loadtxt() ,本篇文章主要讲解用它来读取txt文件。

读取txt文件我们通常使用 numpy 中的 loadtxt()函数

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

注:loadtxt的功能是读入数据文件,这里的数据文件要求每一行数据的格式相同。

也就是说对于下面这样的数据是不符合条件的:

123

1 2 4 3 5

接下来举例讲解函数的功能:

 

1、简单的读取

test.txt

 

1 2 3 4

2 3 4 5

3 4 5 6

4 5 6 7

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

 

数组中的数都为浮点数,原因为Python默认的数字的数据类型为双精度浮点数 

 

2、skiprows=n:指跳过前n行

test.txt

 

A B C D

2 3 4 5

3 4 5 6

4 5 6 7

a = np.loadtxt('test.txt', skiprows=1, dtype=int) print(a)

 

输出:

 

[[2 3 4 5]

[3 4 5 6]

[4 5 6 7]]

 

3、comment=‘#’:如果行的开头为#就会跳过该行

test.txt

 

A B C D

2 3 4 5

3 4 5 6

#A B C D

4 5 6 7

a = np.loadtxt('test.txt', skiprows=1, dtype=int, comments='#') print(a)

 

输出:

 

[[2 3 4 5]

[3 4 5 6]

[4 5 6 7]]

 4、usecols=[0,2]:是指只使用0,2两列,参数类型为list

 

a = np.loadtxt('test.txt', skiprows=1, dtype=int, comments='#',usecols=(0, 2), unpack=True) print(a)

 

输出: 

 

[[2 3 4]

[4 5 6]]

 

unpack是指会把每一列当成一个向量输出, 而不是合并在一起。 如果unpack为false或者参数的话输出结果如下:

[[2 4]

[3 5]

[4 6]]

test.txt

 

A, B, C, D

2, 3, 4, 5

3, 4, 5, 6

#A B C D

4, 5, 6, 7

5、delimiter:数据之间的分隔符。如使用逗号","。

 

6、converters:对数据进行预处理

 

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

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

 

以上就是numpy.loadtxt() 读取txt文件的几种方法。

posted on   一杯明月  阅读(4672)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2020-10-18 ubuntu查看cuda版本和cudnn版本
2020-10-18 conda安装cudatoolkit和cudnn
2020-10-18 pip警告DEPRECATION: The default format will switch to columns in the future
2020-10-18 ubuntu利用conda创建虚拟环境,并安装cuda,cudnn,pytorch
2020-10-18 Ubuntu16.04里安装anaconda3后将python第三方包安装到指定虚拟环境的pyton目录下
2020-10-18 ubuntu16.04使用anaconda创建python虚拟环境
2020-10-18 Ubuntu16.04里安装anaconda3后将python第三方包安装到指定目录下
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示