r"""Vectorized string functions for string-like arrays. Similar to pandas, fields can be accessed through the `.str` attribute for applicable DataArrays. >>> da = xr.DataArray(["some", "text", "in", "an", "array"]) >>> da.str.len() Size
| 142 | |
| 143 | |
| 144 | class StringAccessor(Generic[T_DataArray]): |
| 145 | r"""Vectorized string functions for string-like arrays. |
| 146 | |
| 147 | Similar to pandas, fields can be accessed through the `.str` attribute |
| 148 | for applicable DataArrays. |
| 149 | |
| 150 | >>> da = xr.DataArray(["some", "text", "in", "an", "array"]) |
| 151 | >>> da.str.len() |
| 152 | <xarray.DataArray (dim_0: 5)> Size: 40B |
| 153 | array([4, 4, 2, 2, 5]) |
| 154 | Dimensions without coordinates: dim_0 |
| 155 | |
| 156 | It also implements ``+``, ``*``, and ``%``, which operate as elementwise |
| 157 | versions of the corresponding ``str`` methods. These will automatically |
| 158 | broadcast for array-like inputs. |
| 159 | |
| 160 | >>> da1 = xr.DataArray(["first", "second", "third"], dims=["X"]) |
| 161 | >>> da2 = xr.DataArray([1, 2, 3], dims=["Y"]) |
| 162 | >>> da1.str + da2 |
| 163 | <xarray.DataArray (X: 3, Y: 3)> Size: 252B |
| 164 | array([['first1', 'first2', 'first3'], |
| 165 | ['second1', 'second2', 'second3'], |
| 166 | ['third1', 'third2', 'third3']], dtype='<U7') |
| 167 | Dimensions without coordinates: X, Y |
| 168 | |
| 169 | >>> da1 = xr.DataArray(["a", "b", "c", "d"], dims=["X"]) |
| 170 | >>> reps = xr.DataArray([3, 4], dims=["Y"]) |
| 171 | >>> da1.str * reps |
| 172 | <xarray.DataArray (X: 4, Y: 2)> Size: 128B |
| 173 | array([['aaa', 'aaaa'], |
| 174 | ['bbb', 'bbbb'], |
| 175 | ['ccc', 'cccc'], |
| 176 | ['ddd', 'dddd']], dtype='<U4') |
| 177 | Dimensions without coordinates: X, Y |
| 178 | |
| 179 | >>> da1 = xr.DataArray(["%s_%s", "%s-%s", "%s|%s"], dims=["X"]) |
| 180 | >>> da2 = xr.DataArray([1, 2], dims=["Y"]) |
| 181 | >>> da3 = xr.DataArray([0.1, 0.2], dims=["Z"]) |
| 182 | >>> da1.str % (da2, da3) |
| 183 | <xarray.DataArray (X: 3, Y: 2, Z: 2)> Size: 240B |
| 184 | array([[['1_0.1', '1_0.2'], |
| 185 | ['2_0.1', '2_0.2']], |
| 186 | <BLANKLINE> |
| 187 | [['1-0.1', '1-0.2'], |
| 188 | ['2-0.1', '2-0.2']], |
| 189 | <BLANKLINE> |
| 190 | [['1|0.1', '1|0.2'], |
| 191 | ['2|0.1', '2|0.2']]], dtype='<U5') |
| 192 | Dimensions without coordinates: X, Y, Z |
| 193 | |
| 194 | .. note:: |
| 195 | When using ``%`` formatting with a dict, the values are always used as a |
| 196 | single value, they are not applied elementwise. |
| 197 | |
| 198 | >>> da1 = xr.DataArray(["%(a)s"], dims=["X"]) |
| 199 | >>> da2 = xr.DataArray([1, 2, 3], dims=["Y"]) |
| 200 | >>> da1 % {"a": da2} |
| 201 | <xarray.DataArray (X: 1)> Size: 8B |