1

I want to create a Numpy array, which contains two (Python-) lists. When i try to append an element to one of those lists, the code crashes.

import numpy as np
list0 = [0,0,0]
list1 = [1,1,1]
#list1.append(0)
print(type(list0))
print(type(list1))
array0 = np.array((list0, list1))
array0[0].append(42)
print(array0)    

The confusing thing is that when i uncomment the 4th line, the code works just fine.

The error message i get:

File "test.py", line 10, in <module>
array0[0].append(3)
AttributeError: 'numpy.ndarray' object has no attribute 'append'

I run on python 3.5.1 and numpy 1.10.4

2
  • I just found out that np.array(((0,0,0),(1,1,1))) tries to create a 2d array. This does not happen, if the two lists (e.g. (0,0,0) and (1,1,1)) have different size (e.g. (0,0) and (1,1,1)). A way to initialize an array with two empty lists is to write array0 = np.empty(2, dtype=np.object) array0[:] = [], [] Commented Apr 13, 2016 at 9:51
  • Yes, np.array defaults to making a mulidimensional array. Making an object dtype is the 2nd class backup choice. It may be better to use plain lists, even faster. Commented Apr 13, 2016 at 12:53

2 Answers 2

0

How about using numpy's stack functions? You can use vstack (vertical stack) and hstack (horizontal stack) to append lists/arrays together. You can then also continue to stack more lists/arrays onto the newly created stack. I give three examples below.

Python (saved in file stackingArrays)

import numpy as np

list0 = [0,0,0]
list1 = [1,1,1]

# stack vertically
array_v=np.vstack((list0,list1))
print array_v

# stack horizontally
array_h=np.hstack((list0,list1))
print array_h

# stack more on to stacked array
array_v2=np.vstack((array_v,list1))
print array_v2

Output

> python -i stackingArrays.py
>>> [[0 0 0]
    [1 1 1]]
>>> [0 0 0 1 1 1]
>>> [[0 0 0]
    [1 1 1]
    [1 1 1]]
Sign up to request clarification or add additional context in comments.

Comments

0

the lists has both the same size that's why it become a 2d np array.

therefor you are trying to append a value to one of the rows of the np array (that you can't because it's not a list any more).

I recommend you to use a np array of lists as shown here.

good luck ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.