Home > Software engineering >  Python, create numpy recarray efficiently
Python, create numpy recarray efficiently

Time:04-02

today I am using this code to create a numpy recarray. I am pretty sure it can be done more code efficient. But not exactly sure how to. The input is t and p. Each step says how many seconds and how much power. output is an recarray in seconds.

## New cycle
import numpy as np
t = np.array([30, 60,  60,  60, 120, 120, 150, 600])
p = np.array([0, 200, 300, 400, 350,  50, 400,   0])

time = np.arange(t.sum())
power = np.ones(len(time))

for i in range(len(t)):
    if i ==0:
        power[0:t[i]] = p[i]
    else:
        power[t.cumsum()[i-1] : t.cumsum()[i]] = p[i]
listTuples = [(time[i], power[i]) for i in range(len(time))]
inputArray = np.array(listTuples, dtype=[('time', '<f8'), ('PlossTotal', '<f8')])

CodePudding user response:

I believe the easiest way could be to:

  1. zip lists t and p
  2. use python's list multiplication to create lists of the length you want for each power value (e.g. [1] * 5 is [1, 1, 1, 1, 1])
  3. convert each list to numpy array
  4. concat (stack) all arrays
  5. if you need an array of tuples, you can get it using enumerate

Code:

import numpy as np
t = np.array([30, 60,  60,  60, 120, 120, 150, 600])
p = np.array([0, 200, 300, 400, 350,  50, 400,   0])

res = np.hstack([np.array([ep] * et) for ep, et in zip(p, t)])
res_tuples = = np.array(list(enumerate(res)), dtype=[('time', '<f8'), ('PlossTotal', '<f8')])
  • Related