Python:如何在numpy数组中逐行读取?

Xio*_*g89 -4 python arrays numpy

我想知道我们可以在一个数组中逐行读取.例如:

array([[ 0.28,  0.22,  0.23,  0.27],
       [ 0.12,  0.29,  0.34,  0.21],
       [ 0.44,  0.56,  0.51,  0.65]])
Run Code Online (Sandbox Code Playgroud)

以数组形式读取第一行以执行某些操作,然后继续第二行数组:

array([0.28,0.22,0.23,0.27])
Run Code Online (Sandbox Code Playgroud)

产生上述数组的原因是这两行代码:

from numpy import genfromtxt
single=genfromtxt('single.csv',delimiter=',')
Run Code Online (Sandbox Code Playgroud)

single.csv

0.28,  0.22,  0.23,  0.27
0.12,  0.29,  0.34,  0.21
0.44,  0.56,  0.51,  0.65
Run Code Online (Sandbox Code Playgroud)

使用readlines()看起来像生成列表而不是数组.就我而言,我正在使用csv文件.我试图逐行使用值行而不是一起使用它们以避免内存错误.谁能帮我?

with open('single.csv') as single:
    single=single.readlines()
Run Code Online (Sandbox Code Playgroud)

maa*_*zza 8

您可以使用 np.fromstring

import numpy as np
with open('single.csv') as f:
    lines=f.readlines()
    for line in lines:
        myarray = np.fromstring(line, dtype=float, sep=',')
        print(myarray)
Run Code Online (Sandbox Code Playgroud)

请参阅http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.fromstring.html 以及如何在numpy中将csv读入记录数组?


hpa*_*ulj 7

似乎您没有在 Python 中读取文件的经验。让我在 Ipython 迭代会话中详细介绍一个示例

创建多行文本来模拟您的文件

In [23]: txt="""0.28,  0.22,  0.23,  0.27
0.12,  0.29,  0.34,  0.21
0.44,  0.56,  0.51,  0.65"""
Run Code Online (Sandbox Code Playgroud)

把它分成几行来模拟结果 readlines

In [24]: txt=txt.splitlines(True)

In [25]: txt
Out[25]: 
['0.28,  0.22,  0.23,  0.27\n',
 '0.12,  0.29,  0.34,  0.21\n',
 '0.44,  0.56,  0.51,  0.65']
Run Code Online (Sandbox Code Playgroud)

我可以将它转换为一个数组genfromtxt(你可以将结果传递readlinesgenfromtxt这样。

In [26]: np.genfromtxt(txt, delimiter=',')
Out[26]: 
array([[ 0.28,  0.22,  0.23,  0.27],
       [ 0.12,  0.29,  0.34,  0.21],
       [ 0.44,  0.56,  0.51,  0.65]])
Run Code Online (Sandbox Code Playgroud)

我可以遍历行,剥离\n并拆分“,”

In [27]: for line in txt:
    print line.strip().split(',')
   ....:     
['0.28', '  0.22', '  0.23', '  0.27']
['0.12', '  0.29', '  0.34', '  0.21']
['0.44', '  0.56', '  0.51', '  0.65']
Run Code Online (Sandbox Code Playgroud)

我可以使用列表理解将每个字符串转换为浮点数:

In [28]: for line in txt:                                  
    print [float(x) for x in line.strip().split(',')]
   ....:     
[0.28, 0.22, 0.23, 0.27]
[0.12, 0.29, 0.34, 0.21]
[0.44, 0.56, 0.51, 0.65]
Run Code Online (Sandbox Code Playgroud)

或者通过将迭代放入另一个列表推导式中,我可以获得一个数字列表列表:

In [29]: data=[[float(x) for x in line.strip().split(',')] for line in  txt]

In [30]: data
Out[30]: [[0.28, 0.22, 0.23, 0.27], [0.12, 0.29, 0.34, 0.21], [0.44, 0.56, 0.51, 0.65]]
Run Code Online (Sandbox Code Playgroud)

我可以把它变成一个数组

In [31]: np.array(data)
Out[31]: 
array([[ 0.28,  0.22,  0.23,  0.27],
       [ 0.12,  0.29,  0.34,  0.21],
       [ 0.44,  0.56,  0.51,  0.65]])
Run Code Online (Sandbox Code Playgroud)

genfromtxt 本质上是通过该序列 - 读取行,拆分它们,将字符串转换为值,最后从列表中创建一个数组。

有捷径可走,但我认为您将从详细执行这些步骤中受益。它既是关于基本 Python 字符串和列表操作的练习,也是关于数组的练习。