Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'
append
on an ndarray is ambiguous; to which axis do you want to append the data? Without knowing precisely what your data looks like, I can only provide an example using numpy.concatenate
that I hope will help:
import numpy as np
pixels = np.array([[3,3]])
pix = [4,4]
pixels = np.concatenate((pixels,[pix]),axis=0)
# [[3 3]
# [4 4]]
for root, dirs, files in os.walk(directory):
for file in files:
floc = file
im = Image.open(str(directory) + '\\' + floc)
pix = np.array(im.getdata())
pixels.append(pix)
labels.append(1) # append(i)???
So far ok. But you want to leave pixels
as a list until you are done with the iteration.
pixels = np.array(pixels)
labels = np.array(labels)
You had this indention right in your other question. What happened? previous
Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:
alist = []
for ..
alist.append(...)
arr = np.array(alist)
If names indicate something about the nature of the object I'm less likely to get errors like yours.
I don't understand what you are trying to do with traindata
. I doubt if you need to build it during the loop. pixels
and labels
have the basic information.
That
traindata = np.array([traindata[i][i],traindata[1]], dtype=object)
comes from the previous question. I'm not sure you understand that answer.
traindata = []
traindata.append(pixels)
traindata.append(labels)
if done outside the loop is just
traindata = [pixels, labels]
labels
is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels
is a higher dimension array. What is its shape?
Stop right there. There's no point in turning that list into an array. You can save the list with pickle
.
You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data
Numpy arrays do not have an append method. Use the Numpy append function instead:
import numpy as np
array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely
For example, if array_1 and array_2 have the following values:
array_1 = np.array([1, 2])
array_2 = np.array([3, 4])
If you call np.append without specifying an axis value, like so:
array_3 = np.append(array_1, array_2)
array_3 will have the following value:
array([1, 2, 3, 4])
Else, if you call np.append with an axis value of 0, like so:
array_3 = np.append(array_1, array_2, axis=0)
array_3 will have the following value:
array([[1, 2],
[3, 4]])
More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html