andre
andre

Reputation: 765

Appending to a numpy array

I have the following code:

result = np.zeros((samples,), dtype=[('time', '<f8'), ('data', '<f8', (datalen,))])

I would like to create variable tempresult that accumulates the data result, and once I have accumulated 25000 samples, I would like to perform some operation on it.

So I would like to do something like:

result = np.zeros((samples,), dtype=[('time', '<f8'), ('data', '<f8', (datalen,))])

tempresult.append(result)

if ( len(tempresult[0]  > 25000 )):
   # do something

I tried the answer code but I get exception TypeError: invalid type promotion

result = np.zeros((samples,), dtype=[('time', '<f8'), ('data', '<f8', (datalen,))])

        if self.storeTimeStamp:
            self.storeTimeStamp = False
            self.timestamp = message.timestamp64
            self.oldsamples = 0

        for sample in range(0, samples):
            sstep = self.timestamp + (self.oldsamples + sample) * step
            result[sample] = (sstep, data[sample])

        self.oldsamples = self.oldsamples + samples


        # append
        np.append(self.tempresult, result)

        if len(self.tempresult) < 25000:
            return
        return [self.tempresult]

Upvotes: 0

Views: 158

Answers (1)

hpaulj
hpaulj

Reputation: 231325

1) read np.append docs.

np.append(self.tempresult, result)

is wrong. np.append returns a new array; it does not act in place like list append.

2) np.append is a clumsy interface to np.concatenate. If you don't understand concatenate, you'll get messed up by append.

3) because it makes a new array each time, repeated concatenate is slow. It's much faster to collect a list of arrays, and do one concatenate at the end

4) when using a compound dtype, all inputs to concatenate have to have the same dtype.

Upvotes: 1

Related Questions