繁体   English   中英

从文本文件中读取特定行作为 numpy 数组

[英]Read specific lines from text file as numpy array

我正在尝试以他的格式读取 txt 文件:

[text]
[text]
[text]
1 0 
4 5
3 0 0
[text]
.
.
.

我需要将第 4 到 6 行读取为 numpy 数组。 到目前为止,我有:

 lines=[]
 with open('filename', "r") as f:
     for i, line in enumerate(f):
         if i>=3 and i<=5:
             lines.append(line)
 lines = np.array(lines)

这会将每个所需的行读取为一个元素,但我需要将单独列中的数字作为单独的元素。 有没有解决的办法?

谢谢

您需要将字符串转换为整数:

lines=[]
with open('filename', "r") as f:
    for i, line in enumerate(x.split('\n')):
        if i>=3 and i<=5:
            lines.append([int(y) for y in line.split()])

lines = np.array(lines)
print type(lines)

您可以使用itertools.islice()到 select 行并将结果提供给 Numpy 的genfromtxt() function:

from itertools import islice
import numpy as np

with open('test.txt') as lines:
    array = np.genfromtxt(islice(lines, 3, 6))

print array

您可以使用 numpy 中的skiprowsmax_rows来执行此操作。

array = np.loadtxt(filename,skiprows=3,max_rows=3)

max_rows :在跳过skiprows初始行之后要读取的行数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM