Search code examples
numpytuplespadding

is it possible to pad a numpy array with a tuple?


I'm trying to pad a numpy array with a tuple (the array itself has only tuples)...all I can find is padding an array with 0s or 1s, which I can get to work, but that doesn't help me. Is it possible to pad with a tuple?

The crucial line is :

cells = np.pad(cells, pad_width=1, mode='constant', constant_values=material) 

Replacing material, which is a 4-tuple, with a 0 works fine...but I really need it to be a tuple.

I get the error message:

operands could not be broadcast together with remapped shapes [original->remapped]: (4,) and requested shape (2,2)

Here is the code I am using, but using 0s and 1s instead:

import numpy as np
side_len = 3
a = [1 for x in range(9)]
a = np.array(a)
a = a.reshape(side_len,side_len)
a = np.pad(a, pad_width=1, mode='constant', constant_values=0)

The goal is instead of a list of 1s, to pass a list of tuples, and instead of a constant_values=0, to have constant_values=material, where material is an arbitrary 4-tuple.

A flat list of tuples are passed to this function (the function is not shown here), eg:

[(0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255), (0, 0, 255, 255)]

Which I convert to a numpy array using:

cells = np.array(cells, dtype='i,i,i,i').reshape(side_len,side_len)

Perhaps this is wonky, but the rest of my program just uses lists, I don't need numpy for it; but for this padding issue, I originally was manually iterating over my flat list and doing the padding, which took forever as the list grew, so I thought I'd try numpy because it might be faster.


Solution

  • the solution was:

    import numpy as np
    side_len = 3
    material = (0,0,0,255)
    a = [(255,0,0,255) for x in range(9)]
    a = np.array(a,dtype='i,i,i,i').reshape(side_len,side_len)
    _material = np.array(material,dtype='i,i,i,i')
    a = np.pad(a, pad_width=1, mode='constant', constant_values=_material)
    a
    array([[(  0, 0, 0, 255), (  0, 0, 0, 255), (  0, 0, 0, 255),
            (  0, 0, 0, 255), (  0, 0, 0, 255)],
           [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
            (255, 0, 0, 255), (  0, 0, 0, 255)],
           [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
            (255, 0, 0, 255), (  0, 0, 0, 255)],
           [(  0, 0, 0, 255), (255, 0, 0, 255), (255, 0, 0, 255),
            (255, 0, 0, 255), (  0, 0, 0, 255)],
           [(  0, 0, 0, 255), (  0, 0, 0, 255), (  0, 0, 0, 255),
            (  0, 0, 0, 255), (  0, 0, 0, 255)]],
          dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4')])