I have an array defined as –
import numpy as np
A = np.recarray((3,),dtype=[('x',float), ('y', float), ('z',float)])
Plus another array B which is read from a CSV file as –
>>> print B
[(7.0, 0.0, 7.0) (16.0, 0.0, 1.0)]
When I try to add the elements to array as given below –
for i in range(B.size):
if(B[i][0] != 0.):
A.append((0.,B[i][1],B[i][2]))
if(B[i][1] != 0.):
A.append((B[i][0],0.,B[i][2]))
if(B[i][2] != 0.):
A.append((B[i][0],B[i][1],0.))
I get an error as follows –
File "/usr/lib/python2.7/dist-packages/numpy/core/records.py", line 416, in __getattribute__
raise AttributeError, "record array has no attribute %s" % attr
AttributeError: record array has no attribute append
I am not able to understand where does this string attribute (%s) is coming into picture?
Can someone help out please?
UPDATE:
I changed the code to np.append(A,(0.,B[i][1],B[i][2])), however I get another error as – TypeError: invalid type promotion
Appending to a numpy array is a slow operation because new memory has to be allocated and the entire array has to be copied. Doing this for each row of
Bwould be inefficient. Avoid this if you can.If you know the shape of
Aandminors(B)(see below) in advance, it is best to make an array which is big enough to accomodate both from the beginning.There are many was to do what you asking. @seberg’s
np.lib.recfunctions.stack_arraysidea would make a viable solution as long as the dtypes ofAandBare the same.Here is another possibility, which will work even if
Bhas a different dtype, or is just a ndarray or list of lists.