xarray.core.accessor_str.StringAccessor.format

xarray.core.accessor_str.StringAccessor.format#

StringAccessor.format(*args, **kwargs)[source]#

Perform python string formatting on each element of the DataArray.

This is equivalent to calling str.format on every element of the DataArray. The replacement values can either be a string-like scalar or array-like of string-like values. If array-like, the values will be broadcast and applied elementwiseto the input DataArray.

Note

Array-like values provided as *args will have their dimensions added even if those arguments are not used in any string formatting.

Warning

Array-like arguments are only applied elementwise for *args. For **kwargs, values are used as-is.

Parameters:
  • *args (str or bytes or array-like of str or bytes) – Values for positional formatting. If array-like, the values are broadcast and applied elementwise. The dimensions will be placed at the end of the output array dimensions in the order they are provided.

  • **kwargs (str or bytes or array-like of str or bytes) – Values for keyword-based formatting. These are not broadcast or applied elementwise.

Returns:

formatted (same type as values)

Examples

Create an array to format.

>>> values = xr.DataArray(
...     ["{} is {adj0}", "{} and {} are {adj1}"],
...     dims=["X"],
... )

Set the values to fill.

>>> noun0 = xr.DataArray(
...     ["spam", "egg"],
...     dims=["Y"],
... )
>>> noun1 = xr.DataArray(
...     ["lancelot", "arthur"],
...     dims=["ZZ"],
... )
>>> adj0 = "unexpected"
>>> adj1 = "like a duck"

Insert the values into the array

>>> values.str.format(noun0, noun1, adj0=adj0, adj1=adj1)
<xarray.DataArray (X: 2, Y: 2, ZZ: 2)> Size: 1kB
array([[['spam is unexpected', 'spam is unexpected'],
        ['egg is unexpected', 'egg is unexpected']],

       [['spam and lancelot are like a duck',
         'spam and arthur are like a duck'],
        ['egg and lancelot are like a duck',
         'egg and arthur are like a duck']]], dtype='<U33')
Dimensions without coordinates: X, Y, ZZ

See also

str.format