Numpy Append to Array

2024/10/15 21:15:08

I’m building a project for the Raspberry Pi that turns a relay on and off random times in a specific time window. To manage the time slots, I want to use a two-dimensional array that’s generated daily. So, my Python application needs to empty the previous day’s array, and populate it with the on/off time slots being generated randomly. I can’t figure out how to append my time values to the array. Can someone help me? Here’s my code:

  daily_slots = np.empty([1], dtype=[('onTime', np.dtype(int)), ('offTime', np.dtype(int))])# numpy populates the array with whatever is in memory at that time,# so delete the existing, 'empty' array rowdaily_slots = np.delete(daily_slots, 0, 0)

With that in place, how do I append values? The numpy documentation says I should do something like the following:

daily_slots = np.append(daily_slots, [700, 800])

But that’s not working, I get

Traceback (most recent call last):File "./controller.py", line 351, in <module>init_app()File "./controller.py", line 128, in init_appbuild_daily_slots_array()File "./controller.py", line 307, in build_daily_slots_arraydaily_slots = np.append(daily_slots, [700, 800])File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 3555, in appendreturn concatenate((arr, values), axis=axis)
TypeError: invalid type promotion

I've tried everything I can think of and I've poked and prodded at the numpy documentation and I've not found the answer.

Am I not declaring the array correctly? I want each array 'row' to consist of a two-element array (the ontime and offtime).

Answer

np.append uses np.concatenate. It isn't a true copy of list append. It turns the new value into an array and does concatenate. But to do concatenate with structured arrays, all arrays have to have the same dtype (or at least compatible ones, hence the 'promotion' error.

This works:

In [4]: np.append(daily_slots, np.array((700, 800), dtype=daily_slots.dtype))
Out[4]: 
array([(  0, 1075970048), (700,        800)], dtype=[('onTime', '<i4'), ('offTime', '<i4')])

This also works. I had to add the [] so that the 2nd array was 1d like the first. Without them it is 0d - in effect that's all that np.append adds to the game.

In [6]: np.concatenate((daily_slots, np.array([(700, 800)], dtype=daily_slots.dtype)))
Out[6]: 
array([(  0, 1075970048), (700,        800)], dtype=[('onTime', '<i4'), ('offTime', '<i4')])

For growing and shrinking, a list is usually better. In this case a list of 2 element tuples, or may be a list of a custom class.

If it is a list of tuples, you could wrap it in np.array to turn it into a 2d array for ease of doing calculations.

https://en.xdnf.cn/q/117785.html

Related Q&A

Output of numpy.diff is wrong

heres my problem: I am trying to use numpy to compute (numerical) derivatives, but I am finding some problems in the value the function numpy.diff returns (and numpy.gradient as well). What I find is t…

Calculate Fibonacci numbers up to at least n

I am trying to make a function that allows a user to input a number and the result will be a list containing Fibonacci numbers up to the input and one above if the input is not in the series. For examp…

IEC 62056-21, implement the protocol over a gsm connection

The protocol IEC 62056:21 tells us how to deal with enegy meters, its quite easy!The part where I am stuck is the implementation over a GSM data channel. Normally I would set things like:300 baudrate …

Cannot install plyfile in Anaconda

When u=i try to run the commandconda install plyfilein windows command promptFetching package metadata ...........PackageNotFoundError: Package not found: Package missing in current win-64 channels: -…

Expected singleton: stock.move - Odoo v9 community

Im creating a stock.picking from fleet_vehicle_log_services with this method:@api.multi def create_picking(self):self.ensure_one()vals = {move_lines: self.move_lines.id,origin: self.name}picking = self…

Python Kivy screen manager wiget scope

I am trying to control a screen manager from buttons in a separate class, but I cannot figure out what to set on the button on_press: statements.Kivy file:<HeaderSection>:anchor_x: centeranchor_y…

How do the async and await keywords work, exactly? Whats at the end of the await chain?

I have this code:async def foo(x):yield xyield x + 1async def intermediary(y):await foo(y)def bar():c = intermediary(5)What do I put in bar to get the 5 and the 6 out of c?Im asking because the asynci…

Serial port writing style

I am using two libraries to connect with a port, and two of them uses different styles in writing these commands. I want to understand the difference because I want to use the second one, but it result…

matplotlib plot to fill figure only with data points, no borders, labels, axes,

I am after an extreme form of matplotlibs tight layout. I would like the data points to fill the figure from edge to edge without leaving any borders and without titles, axes, ticks, labels or any othe…

Chromedriver: FileNotFoundError: [WinError 2] The system cannot find the file specified Error

Have looked for an answer, but couldnt find anything. It seems insistent on saying it cant find the file specified and then checks PATH, but cant see it even then :/ Ive put the directory in PATH: http…