str2d.Str2D.pad

Str2D.pad(*args, **kwargs) Str2D[source]

pad pads the data with the fill value specified in the ‘fill’ keyword and is a wrapper around the class method struct_pad which in turn is a wrapper around np.pad.

Parameters:
  • fill (Tuple[str, int], optional) – The fill value for the ‘char’ and ‘alpha’ fields, by default (’ ‘, 0)

  • mode (str, optional) – The padding mode, by default ‘constant’. Other options are documented in np.pad but the only other one that makes sense in a character array context is ‘edge’.

  • args (tuple) – Positional arguments to np.pad.

  • kwargs (dict) – Keyword arguments to np.pad.

Returns:

A new Str2D object with the padded data.

Return type:

Str2D

Examples

Let’s create an instance of Str2D and assign it to the variable a and then pad it.

from str2d import Str2D

a = Str2D('a b c d\ne f g\nh i\nj')
a
a b c d
e f g
h i
j

Now let’s pad the structured array with the fill value ‘.’. The first argument is the number of padding elements to add to the beginning and end of each axis.

a.pad(1, fill=('.', 0))
.........
.a b c d.
.e f g  .
.h i    .
.j      .
.........

If we want to control the padding on each side, we can pass a tuple of integers to the first argument. The first integer is the number of padding elements to add to the beginning of each axis and the second integer is the number of padding elements to add to the end of each axis.

a.pad((1, 2), fill=('.', 0))
..........
.a b c d..
.e f g  ..
.h i    ..
.j      ..
..........
..........

However, you can also control the padding on each side of the array by passing the number of padding elements to add to the beginning and end of each axis as as tuple of tuples. The first tuple is the number of padding elements to add to the beginning and end of the first axis and the second tuple is the number of padding elements to add to the beginning and end of the second axis.

a.pad(((1, 3), (2, 1)), fill=('.', 0))
..........
..a b c d.
..e f g  .
..h i    .
..j      .
..........
..........
..........

Another thing we can do is to pass a different type of padding mode. The default is ‘constant’ which will fill the padding elements with the fill value. However, we can also use ‘edge’ which will fill the padding elements with the nearest edge value.

a.pad(1, mode='edge')
aa b c dd
aa b c dd
ee f g
hh i
jj
jj