numpy.loadtxt

numpy.loadtxt

numpy.loadtxt(fnamedtype=<class 'float'>comments='#'delimiter=Noneconverters=Noneskiprows=0usecols=Noneunpack=Falsendmin=0encoding='bytes'max_rows=None*like=None)

Load data from a text file.

Each row in the text file must have the same number of values.

Parameters

fnamefile, str, pathlib.Path, list of str, generator

File, filename, list, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines.

dtypedata-type, optional

Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type.

commentsstr or sequence of str, optional

The characters or list of characters used to indicate the start of a comment. None implies no comments. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is ‘#’.

delimiterstr, optional

The string used to separate values. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is whitespace.

convertersdict, optional

A dictionary mapping column number to a function that will parse the column string into the desired value. E.g., if column 0 is a date string: converters = {0: datestr2num}. Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}. Default: None.

skiprowsint, optional

Skip the first skiprows lines, including comments; default: 0.

usecolsint or sequence, optional

Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read.

Changed in version 1.11.0: When a single column has to be read it is possible to use an integer instead of a tuple. E.g usecols = 3 reads the fourth column the same way as usecols = (3,) would.

unpackbool, optional

If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False.

ndminint, optional

The returned array will have at least ndmin dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2.

New in version 1.6.0.

encodingstr, optional

Encoding used to decode the inputfile. Does not apply to input streams. The special value ‘bytes’ enables backward compatibility workarounds that ensures you receive byte arrays as results if possible and passes ‘latin1’ encoded strings to converters. Override this value to receive unicode arrays and pass strings as input to converters. If set to None the system default is used. The default value is ‘bytes’.

New in version 1.14.0.

max_rowsint, optional

Read max_rows lines of content after skiprows lines. The default is to read all the lines.

New in version 1.16.0.

likearray_like

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

New in version 1.20.0.

Returns

outndarray

Data read from the text file.

numpy.loadtxt 用法 读取txt文件
numpy.loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
上面给出了loadtxt所有的关键字参数, 这里我们可以来一一解释并给出示例

import numpy as np
# 首先给出最简单的loadtxt的代码,实际上就是直接写文件名, 其他关键字参数都是默认的.
a = np.loadtxt('./data/test.txt')
print(a)  # a为浮点数的原因为Python默认的数字的数据类型为双精度浮点数
[[ 1.  2.  3.  4.]
 [ 2.  3.  4.  5.]
 [ 3.  4.  5.  6.]
 [ 4.  5.  6.  7.]]
# 这里的skiprows是指跳过前1行, 如果设置skiprows=2, 就会跳过前两行,数据类型设置为整形.
a = np.loadtxt('./data/test.txt', skiprows=1, dtype=int)
print(a)
[[2 3 4 5]
 [3 4 5 6]
 [4 5 6 7]]
# 这里的comment的是指, 如果行的开头为#就会跳过该行
a = np.loadtxt('./data/test1.txt', dtype=int, skiprows=1, comments='#')
print(a)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
# 这里的usecols是指只使用0,2两列, unpack是指会把每一列当成一个向量输出, 而不是合并在一起。
(a, b) = np.loadtxt('./data/test2.txt', dtype=int, skiprows=1, comments='#', delimiter=',', usecols=(0, 2), unpack=True)
print(a, b)
[1 4 7] [3 6 9]
# 最后介绍converters参数, 这个是对数据进行预处理的参数, 我们可以先定义一个函数, 这里的converters是一个字典, 表示第零列使用函数add_one来进行预处理
def add_one(x):
    return int(x)+1  # 注意到这里使用的字符的数据结构

(a, b) = np.loadtxt('./data/test2.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]

参考文章:numpy.loadtxt() 用法_我是天才很好的博客-CSDN博客_loadtxt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值