AttributeError: 'numpy.ndarray' object has no attribute 'append'

PythonMatplotlib

Python Problem Overview


I am trying to run the code presented on the second page:

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/video-lectures/lecture-20/lec20.pdf

At the bottom of the code you have to add these lines:

simFlips(100,100)

show()

Here is the error that I get when I run it on ubuntu:

Traceback (most recent call last):
  File "coin.py", line 36, in <module>
    simFlips(100,100)
  File "coin.py", line 16, in simFlips
    diffs.append(abs(heads - tails))
AttributeError: 'numpy.ndarray' object has no attribute 'append'

Please tell me what I'm doing wrong that gives me the last error. Thanks in advance!

Python Solutions


Solution 1 - Python

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at https://stackoverflow.com/questions/9775297/append-a-numpy-array-to-a-numpy-array.

Solution 2 - Python

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

Solution 3 - Python

You will have to use numpy function to append numpy arrays. Append will workk only for ordinary lists not numpy arrays.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvahshiView Question on Stackoverflow
Solution 1 - PythonArpita BiswasView Answer on Stackoverflow
Solution 2 - PythonEduardo FreitasView Answer on Stackoverflow
Solution 3 - PythonZamal AliView Answer on Stackoverflow