Reputation: 33
I am struggling with a program I am making on the part where I have to store values that I get from my loop in an array.
What I tried to do is to make an empty array called M. Then for every new value "a" calculated in a loop I use the command M.append(a) to add the value a to the array M.
The thing is, python says this error : 'numpy.ndarray' object has no attribute 'append'
and I don't know how to fix it.
Here is my code :
import numpy as np
from matplotlib import pyplot as plt
with open('expFcn0.txt') as f:
M = np.array([])
print(M)
lines = f.readlines()
x = [float(line.split()[0]) for line in lines]
y = [float(line.split()[1]) for line in lines]
for i in range(0,181):
a=np.log(y[i])/x[i]
print(a)
i=i+1
M.append(a)
print(M)
plt.plot(x, y, 'r--')
plt.xlabel('Time')
plt.ylabel('Biomass')
plt.title('Exponential Function')
plt.show()
Thank you very much!
Upvotes: 1
Views: 12061
Reputation: 19260
Other answers explain that numpy arrays do not have an .append()
method and point to numpy.append
. Using numpy.append
, however, is bad practice because it creates a new array each time. A better solution is to create one numpy and fill it during the for
loop (see end of answer).
An even better solution would make use of numpy's broadcasting. That's a core feature of numpy, and it's what helps make numpy fast.
import numpy as np
with open('expFcn0.txt') as f:
lines = f.readlines()
x = np.array([float(line.split()[0]) for line in lines])
y = np.array([float(line.split()[1]) for line in lines])
M = np.log(y) / x
You can also look into numpy.loadtxt
to read the file into a numpy array directly.
How to fill a numpy array in a for
loop:
import numpy as np
with open('expFcn0.txt') as f:
lines = f.readlines()
x = [float(line.split()[0]) for line in lines]
y = [float(line.split()[1]) for line in lines]
M = np.zeros(181)
for i in range(181):
a = np.log(y[i])/x[i]
print(a)
M[i] = a
Upvotes: 1
Reputation: 2442
Numpy arrays do not have an append method. Use the Numpy append function instead:
M = np.append(M, a)
Upvotes: 0
Reputation: 1893
Numpy arrays don't have a method append()
. You need to use np.append(array, values)
as per the documentation, or for your case, np.append(M, a)
.
Upvotes: 3