22

I have a problem using the function numpy.append. I wrote the following function as part of a larger piece of code, however, my error is reproduced in the folowing:

data = [
         [
          '3.5', '3', '0', '0', '15', '6', 
          '441', 'some text', 'some more complicated data'
         ], 
         [
          '4.5', '5', '1', '10', '165', '0', 
          '1', 'some other text', 'some even more complicated data'
         ]
       ]

def GetNumpyArrey(self, index):
    r = np.array([])
    for line in data:
        np.append(r, float(line[index]))

    print r

index < 6. the result is:

>> []

what am I doing wrong?

Thanks a lot !

Nilesh
  • 20,521
  • 16
  • 92
  • 148
mm_
  • 1,566
  • 2
  • 18
  • 37
  • 2
    http://stackoverflow.com/questions/5064822/numpy-how-to-add-items-into-an-array – avasal Nov 22 '12 at 04:59
  • 1
    As @BrenBarn points out, there is no reason to use `numpy.append` here. The most efficient thing to do is initially allocate `r` to `len(data)`. If you don't know the length in advance (e.g. reading from a file), then @BrenBarn's suggestion of creating a list and converting to an array is best. – DaveP Nov 22 '12 at 08:27

1 Answers1

40

Unlike the list append method, numpy's append does not append in-place. It returns a new array with the extra elements appended. So you'd need to do r = np.append(r, float(line[index])).

Building up numpy arrays in this way is inefficient, though. It's better to just build your list as a Python list and then make a numpy array at the end.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384