用NumPy从文件中读取非统一数据 [英] Reading non-uniform data from file into array with NumPy

查看:112
本文介绍了用NumPy从文件中读取非统一数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个如下所示的文本文件:


33 3

46 12

23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16

33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19

41 32 41 33 42 32 42 33

我想把每一行读到一个单独的整数数组中,如(伪代码)所示:

 
currentArray = firstLine
执行currentArray

在第一次迭代中,currentArray将会是

lockquote

array([33,3])


,在第二次迭代中,currentArray将是

lockquote

数组直到最后一次迭代,当currentArray将是



array([41,32,41,33,42,32,42,33])



<基本上,我想有numpy函数的函数loadtxt:


currentArray = loadtxt('scienceVertices.txt',usecols =())

除了usecols之外,还可以指定行,例如


currentArray = loadtxt('scienceVertices.txt',userows =(line))


解决方案

这里是一行:

  arrays = [np.array(map (int,line.split()))for open in line('scienceVertices.txt')] 

数组是numpy数组的列表。


Suppose I have a text file that looks like this:

33 3
46 12
23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16
33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19
41 32 41 33 42 32 42 33

I would like to read each line into a separate array of integers, as in (pseudo code):

for line in textfile:  
    currentArray = firstLine  
    do stuff with currentArray

where in the first iteration, currentArray would be

array([33, 3])

and in the second iteration, currentArray would be

array([46, 12])

until the last iteration, when currentArray would be

array([41, 32, 41, 33, 42, 32, 42, 33])

Basically, I would like to have the functionality of the numpy function loadtxt:

currentArray = loadtxt('scienceVertices.txt', usecols=() )

Except instead of usecols, being able to specify the row, e.g.,

currentArray = loadtxt('scienceVertices.txt', userows=(line) )

解决方案

Here's a one-liner:

arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]

arrays is a list of numpy arrays.

这篇关于用NumPy从文件中读取非统一数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆