[newbie] confusion concerning fetching an element in a 2d-array

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Mar 25 07:01:37 EDT 2014


On Tue, 25 Mar 2014 03:26:26 -0700, Jean Dubois wrote:

> I'm confused by the behaviour of the following python-script I wrote:
> 
> #!/usr/bin/env python
> #I first made a data file 'test.dat' with the following content 
> #1.0 2 3
> #4 5 6.0
> #7 8 9
> import numpy as np
> lines=[line.strip() for line in open('test.dat')] 
> #convert lines-list to numpy-array
> array_lines=np.array(lines)
> #fetch element at 2nd row, 2nd column: 
> print array_lines[1, 1]
> 
> 
> When running the script I always get the following error: IndexError:
> invalid index
> 
> Can anyone here explain me what I am doing wrong and how to fix it?

Yes. Inspect the array by printing it, and you'll see that it is a one-
dimensional array, not two, and the entries are strings:


py> import numpy as np
py> # simulate a text file
... data = """1.0 2 3
... 4 5 6.0
... 7 8 9"""
py> lines=[line.strip() for line in data.split('\n')]
py> # convert lines-list to numpy-array
... array_lines = np.array(lines)
py> print array_lines
['1.0 2 3' '4 5 6.0' '7 8 9']


The interactive interpreter is your friend! You never need to guess what 
the problem is, Python has powerful introspection abilities, one of the 
most powerful is also one of the simplest: print. Another powerful tool 
in the interactive interpreter is help().

So, what to do about it? Firstly, convert your string read from a file 
into numbers, then build your array. Here's one way:

py> values = [float(s) for s in data.split()]
py> print values
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
py> array_lines = np.array(values)
py> array_lines = array_lines.reshape(3, 3)
py> print array_lines
[[ 1.  2.  3.]
 [ 4.  5.  6.]
 [ 7.  8.  9.]]


There may be other ways to do this, but that works for me.


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list