Repository navigation
Expand file tree
/
Copy pathaccessor_str.py
More file actions
2901 lines (2465 loc) · 97.4 KB
/
Copy pathaccessor_str.py
File metadata and controls
2901 lines (2465 loc) · 97.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The StringAccessor class defined below is an adaptation of the
# pandas string methods source code (see pd.core.strings)
# For reference, here is a copy of the pandas copyright notice:
# (c) 2011-2012, Lambda Foundry, Inc. and PyData Development Team
# All rights reserved.
# Copyright (c) 2008-2011 AQR Capital Management, LLC
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the copyright holder nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import codecs
import re
import textwrap
from collections.abc import Callable, Hashable, Mapping
from functools import reduce
from operator import or_ as set_union
from re import Pattern
from typing import TYPE_CHECKING, Any, Generic
from unicodedata import normalize
import numpy as np
from xarray.core import duck_array_ops
from xarray.core.types import T_DataArray
if TYPE_CHECKING:
from numpy.typing import DTypeLike
from xarray.core.dataarray import DataArray
_cpython_optimized_encoders = (
"utf-8",
"utf8",
"latin-1",
"latin1",
"iso-8859-1",
"mbcs",
"ascii",
)
_cpython_optimized_decoders = _cpython_optimized_encoders + ("utf-16", "utf-32")
def _contains_obj_type(*, pat: Any, checker: Any) -> bool:
"""Determine if the object fits some rule or is array of objects that do so."""
if isinstance(checker, type):
targtype = checker
checker = lambda x: isinstance(x, targtype)
if checker(pat):
return True
# If it is not an object array it can't contain compiled re
if getattr(pat, "dtype", "no") != np.object_:
return False
return _apply_str_ufunc(func=checker, obj=pat).all()
def _contains_str_like(pat: Any) -> bool:
"""Determine if the object is a str-like or array of str-like."""
if isinstance(pat, str | bytes):
return True
if not hasattr(pat, "dtype"):
return False
return pat.dtype.kind in ["U", "S"]
def _contains_compiled_re(pat: Any) -> bool:
"""Determine if the object is a compiled re or array of compiled re."""
return _contains_obj_type(pat=pat, checker=re.Pattern)
def _contains_callable(pat: Any) -> bool:
"""Determine if the object is a callable or array of callables."""
return _contains_obj_type(pat=pat, checker=callable)
def _apply_str_ufunc(
*,
func: Callable,
obj: Any,
dtype: DTypeLike | None = None,
output_core_dims: list | tuple = ((),),
output_sizes: Mapping[Any, int] | None = None,
func_args: tuple = (),
func_kwargs: Mapping = {},
) -> Any:
# TODO handling of na values ?
if dtype is None:
dtype = obj.dtype
dask_gufunc_kwargs = dict()
if output_sizes is not None:
dask_gufunc_kwargs["output_sizes"] = output_sizes
from xarray.computation.apply_ufunc import apply_ufunc
return apply_ufunc(
func,
obj,
*func_args,
vectorize=True,
dask="parallelized",
output_dtypes=[dtype],
output_core_dims=output_core_dims,
dask_gufunc_kwargs=dask_gufunc_kwargs,
**func_kwargs,
)
class StringAccessor(Generic[T_DataArray]):
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()
<xarray.DataArray (dim_0: 5)> Size: 40B
array([4, 4, 2, 2, 5])
Dimensions without coordinates: dim_0
It also implements ``+``, ``*``, and ``%``, which operate as elementwise
versions of the corresponding ``str`` methods. These will automatically
broadcast for array-like inputs.
>>> da1 = xr.DataArray(["first", "second", "third"], dims=["X"])
>>> da2 = xr.DataArray([1, 2, 3], dims=["Y"])
>>> da1.str + da2
<xarray.DataArray (X: 3, Y: 3)> Size: 252B
array([['first1', 'first2', 'first3'],
['second1', 'second2', 'second3'],
['third1', 'third2', 'third3']], dtype='<U7')
Dimensions without coordinates: X, Y
>>> da1 = xr.DataArray(["a", "b", "c", "d"], dims=["X"])
>>> reps = xr.DataArray([3, 4], dims=["Y"])
>>> da1.str * reps
<xarray.DataArray (X: 4, Y: 2)> Size: 128B
array([['aaa', 'aaaa'],
['bbb', 'bbbb'],
['ccc', 'cccc'],
['ddd', 'dddd']], dtype='<U4')
Dimensions without coordinates: X, Y
>>> da1 = xr.DataArray(["%s_%s", "%s-%s", "%s|%s"], dims=["X"])
>>> da2 = xr.DataArray([1, 2], dims=["Y"])
>>> da3 = xr.DataArray([0.1, 0.2], dims=["Z"])
>>> da1.str % (da2, da3)
<xarray.DataArray (X: 3, Y: 2, Z: 2)> Size: 240B
array([[['1_0.1', '1_0.2'],
['2_0.1', '2_0.2']],
<BLANKLINE>
[['1-0.1', '1-0.2'],
['2-0.1', '2-0.2']],
<BLANKLINE>
[['1|0.1', '1|0.2'],
['2|0.1', '2|0.2']]], dtype='<U5')
Dimensions without coordinates: X, Y, Z
.. note::
When using ``%`` formatting with a dict, the values are always used as a
single value, they are not applied elementwise.
>>> da1 = xr.DataArray(["%(a)s"], dims=["X"])
>>> da2 = xr.DataArray([1, 2, 3], dims=["Y"])
>>> da1 % {"a": da2}
<xarray.DataArray (X: 1)> Size: 8B
array(['<xarray.DataArray (Y: 3)> Size: 24B\narray([1, 2, 3])\nDimensions without coordinates: Y'],
dtype=object)
Dimensions without coordinates: X
"""
__slots__ = ("_obj",)
def __init__(self, obj: T_DataArray) -> None:
self._obj = obj
def _stringify(self, invar: Any) -> str | bytes | Any:
"""
Convert a string-like to the correct string/bytes type.
This is mostly here to tell mypy a pattern is a str/bytes not a re.Pattern.
"""
if hasattr(invar, "astype"):
return invar.astype(self._obj.dtype.kind)
else:
return self._obj.dtype.type(invar)
def _apply(
self,
*,
func: Callable,
dtype: DTypeLike | None = None,
output_core_dims: list | tuple = ((),),
output_sizes: Mapping[Any, int] | None = None,
func_args: tuple = (),
func_kwargs: Mapping = {},
) -> T_DataArray:
return _apply_str_ufunc(
obj=self._obj,
func=func,
dtype=dtype,
output_core_dims=output_core_dims,
output_sizes=output_sizes,
func_args=func_args,
func_kwargs=func_kwargs,
)
def _re_compile(
self,
*,
pat: str | bytes | Pattern | Any,
flags: int = 0,
case: bool | None = None,
) -> Pattern | Any:
is_compiled_re = isinstance(pat, re.Pattern)
if is_compiled_re and flags != 0:
raise ValueError("Flags cannot be set when pat is a compiled regex.")
if is_compiled_re and case is not None:
raise ValueError("Case cannot be set when pat is a compiled regex.")
if is_compiled_re:
# no-op, needed to tell mypy this isn't a string
return re.compile(pat)
if case is None:
case = True
# The case is handled by the re flags internally.
# Add it to the flags if necessary.
if not case:
flags |= re.IGNORECASE
if getattr(pat, "dtype", None) != np.object_:
pat = self._stringify(pat)
def func(x):
return re.compile(x, flags=flags)
if isinstance(pat, np.ndarray):
# apply_ufunc doesn't work for numpy arrays with output object dtypes
func_ = np.vectorize(func)
return func_(pat)
else:
return _apply_str_ufunc(func=func, obj=pat, dtype=np.object_)
def len(self) -> T_DataArray:
"""
Compute the length of each string in the array.
Returns
-------
lengths array : array of int
"""
return self._apply(func=len, dtype=int)
def __getitem__(
self,
key: int | slice,
) -> T_DataArray:
if isinstance(key, slice):
return self.slice(start=key.start, stop=key.stop, step=key.step)
else:
return self.get(key)
def __add__(self, other: Any) -> T_DataArray:
return self.cat(other, sep="")
def __mul__(
self,
num: int | Any,
) -> T_DataArray:
return self.repeat(num)
def __mod__(
self,
other: Any,
) -> T_DataArray:
if isinstance(other, dict):
other = {key: self._stringify(val) for key, val in other.items()}
return self._apply(func=lambda x: x % other)
elif isinstance(other, tuple):
other = tuple(self._stringify(x) for x in other)
return self._apply(func=lambda x, *y: x % y, func_args=other)
else:
return self._apply(func=lambda x, y: x % y, func_args=(other,))
def get(
self,
i: int | Any,
default: str | bytes = "",
) -> T_DataArray:
"""
Extract character number `i` from each string in the array.
If `i` is array-like, they are broadcast against the array and
applied elementwise.
Parameters
----------
i : int or array-like of int
Position of element to extract.
If array-like, it is broadcast.
default : str or bytes, default: ""
Value for out-of-range index.
Returns
-------
items : array of object
"""
def f(x, iind):
islice = slice(-1, None) if iind == -1 else slice(iind, iind + 1)
item = x[islice]
return item or default
return self._apply(func=f, func_args=(i,))
def slice(
self,
start: int | Any | None = None,
stop: int | Any | None = None,
step: int | Any | None = None,
) -> T_DataArray:
"""
Slice substrings from each string in the array.
If `start`, `stop`, or 'step` is array-like, they are broadcast
against the array and applied elementwise.
Parameters
----------
start : int or array-like of int, optional
Start position for slice operation.
If array-like, it is broadcast.
stop : int or array-like of int, optional
Stop position for slice operation.
If array-like, it is broadcast.
step : int or array-like of int, optional
Step size for slice operation.
If array-like, it is broadcast.
Returns
-------
sliced strings : same type as values
"""
f = lambda x, istart, istop, istep: x[slice(istart, istop, istep)]
return self._apply(func=f, func_args=(start, stop, step))
def slice_replace(
self,
start: int | Any | None = None,
stop: int | Any | None = None,
repl: str | bytes | Any = "",
) -> T_DataArray:
"""
Replace a positional slice of a string with another value.
If `start`, `stop`, or 'repl` is array-like, they are broadcast
against the array and applied elementwise.
Parameters
----------
start : int or array-like of int, optional
Left index position to use for the slice. If not specified (None),
the slice is unbounded on the left, i.e. slice from the start
of the string. If array-like, it is broadcast.
stop : int or array-like of int, optional
Right index position to use for the slice. If not specified (None),
the slice is unbounded on the right, i.e. slice until the
end of the string. If array-like, it is broadcast.
repl : str or array-like of str, default: ""
String for replacement. If not specified, the sliced region
is replaced with an empty string. If array-like, it is broadcast.
Returns
-------
replaced : same type as values
"""
repl = self._stringify(repl)
def func(x, istart, istop, irepl):
if len(x[istart:istop]) == 0:
local_stop = istart
else:
local_stop = istop
y = self._stringify("")
if istart is not None:
y += x[:istart]
y += irepl
if istop is not None:
y += x[local_stop:]
return y
return self._apply(func=func, func_args=(start, stop, repl))
def cat(self, *others, sep: str | bytes | Any = "") -> T_DataArray:
"""
Concatenate strings elementwise in the DataArray with other strings.
The other strings can either be string scalars or other array-like.
Dimensions are automatically broadcast together.
An optional separator `sep` can also be specified. If `sep` is
array-like, it is broadcast against the array and applied elementwise.
Parameters
----------
*others : str or array-like of str
Strings or array-like of strings to concatenate elementwise with
the current DataArray.
sep : str or array-like of str, default: "".
Separator to use between strings.
It is broadcast in the same way as the other input strings.
If array-like, its dimensions will be placed at the end of the output array dimensions.
Returns
-------
concatenated : same type as values
Examples
--------
Create a string array
>>> myarray = xr.DataArray(
... ["11111", "4"],
... dims=["X"],
... )
Create some arrays to concatenate with it
>>> values_1 = xr.DataArray(
... ["a", "bb", "cccc"],
... dims=["Y"],
... )
>>> values_2 = np.array(3.4)
>>> values_3 = ""
>>> values_4 = np.array("test", dtype=np.str_)
Determine the separator to use
>>> seps = xr.DataArray(
... [" ", ", "],
... dims=["ZZ"],
... )
Concatenate the arrays using the separator
>>> myarray.str.cat(values_1, values_2, values_3, values_4, sep=seps)
<xarray.DataArray (X: 2, Y: 3, ZZ: 2)> Size: 1kB
array([[['11111 a 3.4 test', '11111, a, 3.4, , test'],
['11111 bb 3.4 test', '11111, bb, 3.4, , test'],
['11111 cccc 3.4 test', '11111, cccc, 3.4, , test']],
<BLANKLINE>
[['4 a 3.4 test', '4, a, 3.4, , test'],
['4 bb 3.4 test', '4, bb, 3.4, , test'],
['4 cccc 3.4 test', '4, cccc, 3.4, , test']]], dtype='<U24')
Dimensions without coordinates: X, Y, ZZ
See Also
--------
pandas.Series.str.cat
str.join
"""
sep = self._stringify(sep)
others = tuple(self._stringify(x) for x in others)
others = others + (sep,)
# sep will go at the end of the input arguments.
func = lambda *x: x[-1].join(x[:-1])
return self._apply(
func=func,
func_args=others,
dtype=self._obj.dtype.kind,
)
def join(
self,
dim: Hashable = None,
sep: str | bytes | Any = "",
) -> T_DataArray:
"""
Concatenate strings in a DataArray along a particular dimension.
An optional separator `sep` can also be specified. If `sep` is
array-like, it is broadcast against the array and applied elementwise.
Parameters
----------
dim : hashable, optional
Dimension along which the strings should be concatenated.
Only one dimension is allowed at a time.
Optional for 0D or 1D DataArrays, required for multidimensional DataArrays.
sep : str or array-like, default: "".
Separator to use between strings.
It is broadcast in the same way as the other input strings.
If array-like, its dimensions will be placed at the end of the output array dimensions.
Returns
-------
joined : same type as values
Examples
--------
Create an array
>>> values = xr.DataArray(
... [["a", "bab", "abc"], ["abcd", "", "abcdef"]],
... dims=["X", "Y"],
... )
Determine the separator
>>> seps = xr.DataArray(
... ["-", "_"],
... dims=["ZZ"],
... )
Join the strings along a given dimension
>>> values.str.join(dim="Y", sep=seps)
<xarray.DataArray (X: 2, ZZ: 2)> Size: 192B
array([['a-bab-abc', 'a_bab_abc'],
['abcd--abcdef', 'abcd__abcdef']], dtype='<U12')
Dimensions without coordinates: X, ZZ
See Also
--------
pandas.Series.str.join
str.join
"""
if self._obj.ndim > 1 and dim is None:
raise ValueError("Dimension must be specified for multidimensional arrays.")
if self._obj.ndim > 1:
# Move the target dimension to the start and split along it
dimshifted = list(self._obj.transpose(dim, ...))
elif self._obj.ndim == 1:
dimshifted = list(self._obj)
else:
dimshifted = [self._obj]
start, *others = dimshifted
# concatenate the resulting arrays
return start.str.cat(*others, sep=sep)
def format(
self,
*args: Any,
**kwargs: Any,
) -> T_DataArray:
"""
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']],
<BLANKLINE>
[['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
"""
args = tuple(self._stringify(x) for x in args)
kwargs = {key: self._stringify(val) for key, val in kwargs.items()}
return self._apply(
func=self._obj.dtype.type.format,
func_args=args,
func_kwargs={"kwargs": kwargs},
)
def capitalize(self) -> T_DataArray:
"""
Convert strings in the array to be capitalized.
Returns
-------
capitalized : same type as values
Examples
--------
>>> da = xr.DataArray(
... ["temperature", "PRESSURE", "PreCipiTation", "daily rainfall"], dims="x"
... )
>>> da
<xarray.DataArray (x: 4)> Size: 224B
array(['temperature', 'PRESSURE', 'PreCipiTation', 'daily rainfall'],
dtype='<U14')
Dimensions without coordinates: x
>>> capitalized = da.str.capitalize()
>>> capitalized
<xarray.DataArray (x: 4)> Size: 224B
array(['Temperature', 'Pressure', 'Precipitation', 'Daily rainfall'],
dtype='<U14')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.capitalize())
def lower(self) -> T_DataArray:
"""
Convert strings in the array to lowercase.
Returns
-------
lowered : same type as values
Examples
--------
>>> da = xr.DataArray(["Temperature", "PRESSURE"], dims="x")
>>> da
<xarray.DataArray (x: 2)> Size: 88B
array(['Temperature', 'PRESSURE'], dtype='<U11')
Dimensions without coordinates: x
>>> lowered = da.str.lower()
>>> lowered
<xarray.DataArray (x: 2)> Size: 88B
array(['temperature', 'pressure'], dtype='<U11')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.lower())
def swapcase(self) -> T_DataArray:
"""
Convert strings in the array to be swapcased.
Returns
-------
swapcased : same type as values
Examples
--------
>>> import xarray as xr
>>> da = xr.DataArray(["temperature", "PRESSURE", "HuMiDiTy"], dims="x")
>>> da
<xarray.DataArray (x: 3)> Size: 132B
array(['temperature', 'PRESSURE', 'HuMiDiTy'], dtype='<U11')
Dimensions without coordinates: x
>>> swapcased = da.str.swapcase()
>>> swapcased
<xarray.DataArray (x: 3)> Size: 132B
array(['TEMPERATURE', 'pressure', 'hUmIdItY'], dtype='<U11')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.swapcase())
def title(self) -> T_DataArray:
"""
Convert strings in the array to titlecase.
Returns
-------
titled : same type as values
Examples
--------
>>> da = xr.DataArray(["temperature", "PRESSURE", "HuMiDiTy"], dims="x")
>>> da
<xarray.DataArray (x: 3)> Size: 132B
array(['temperature', 'PRESSURE', 'HuMiDiTy'], dtype='<U11')
Dimensions without coordinates: x
>>> titled = da.str.title()
>>> titled
<xarray.DataArray (x: 3)> Size: 132B
array(['Temperature', 'Pressure', 'Humidity'], dtype='<U11')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.title())
def upper(self) -> T_DataArray:
"""
Convert strings in the array to uppercase.
Returns
-------
uppered : same type as values
Examples
--------
>>> da = xr.DataArray(["temperature", "HuMiDiTy"], dims="x")
>>> da
<xarray.DataArray (x: 2)> Size: 88B
array(['temperature', 'HuMiDiTy'], dtype='<U11')
Dimensions without coordinates: x
>>> uppered = da.str.upper()
>>> uppered
<xarray.DataArray (x: 2)> Size: 88B
array(['TEMPERATURE', 'HUMIDITY'], dtype='<U11')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.upper())
def casefold(self) -> T_DataArray:
"""
Convert strings in the array to be casefolded.
Casefolding is similar to converting to lowercase,
but removes all case distinctions.
This is important in some languages that have more complicated
cases and case conversions. For example,
the 'ß' character in German is case-folded to 'ss', whereas it is lowercased
to 'ß'.
Returns
-------
casefolded : same type as values
Examples
--------
>>> da = xr.DataArray(["TEMPERATURE", "HuMiDiTy"], dims="x")
>>> da
<xarray.DataArray (x: 2)> Size: 88B
array(['TEMPERATURE', 'HuMiDiTy'], dtype='<U11')
Dimensions without coordinates: x
>>> casefolded = da.str.casefold()
>>> casefolded
<xarray.DataArray (x: 2)> Size: 88B
array(['temperature', 'humidity'], dtype='<U11')
Dimensions without coordinates: x
>>> da = xr.DataArray(["ß", "İ"], dims="x")
>>> da
<xarray.DataArray (x: 2)> Size: 8B
array(['ß', 'İ'], dtype='<U1')
Dimensions without coordinates: x
>>> casefolded = da.str.casefold()
>>> casefolded
<xarray.DataArray (x: 2)> Size: 16B
array(['ss', 'i̇'], dtype='<U2')
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.casefold())
def normalize(
self,
form: str,
) -> T_DataArray:
"""
Return the Unicode normal form for the strings in the datarray.
For more information on the forms, see the documentation for
:func:`unicodedata.normalize`.
Parameters
----------
form : {"NFC", "NFKC", "NFD", "NFKD"}
Unicode form.
Returns
-------
normalized : same type as values
"""
return self._apply(func=lambda x: normalize(form, x)) # type: ignore[arg-type]
def isalnum(self) -> T_DataArray:
"""
Check whether all characters in each string are alphanumeric.
Returns
-------
isalnum : array of bool
Array of boolean values with the same shape as the original array.
Examples
--------
>>> da = xr.DataArray(["H2O", "NaCl-"], dims="x")
>>> da
<xarray.DataArray (x: 2)> Size: 40B
array(['H2O', 'NaCl-'], dtype='<U5')
Dimensions without coordinates: x
>>> isalnum = da.str.isalnum()
>>> isalnum
<xarray.DataArray (x: 2)> Size: 2B
array([ True, False])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.isalnum(), dtype=bool)
def isalpha(self) -> T_DataArray:
"""
Check whether all characters in each string are alphabetic.
Returns
-------
isalpha : array of bool
Array of boolean values with the same shape as the original array.
Examples
--------
>>> da = xr.DataArray(["Mn", "H2O", "NaCl-"], dims="x")
>>> da
<xarray.DataArray (x: 3)> Size: 60B
array(['Mn', 'H2O', 'NaCl-'], dtype='<U5')
Dimensions without coordinates: x
>>> isalpha = da.str.isalpha()
>>> isalpha
<xarray.DataArray (x: 3)> Size: 3B
array([ True, False, False])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.isalpha(), dtype=bool)
def isdecimal(self) -> T_DataArray:
"""
Check whether all characters in each string are decimal.
Returns
-------
isdecimal : array of bool
Array of boolean values with the same shape as the original array.
Examples
--------
>>> da = xr.DataArray(["2.3", "123", "0"], dims="x")
>>> da
<xarray.DataArray (x: 3)> Size: 36B
array(['2.3', '123', '0'], dtype='<U3')
Dimensions without coordinates: x
>>> isdecimal = da.str.isdecimal()
>>> isdecimal
<xarray.DataArray (x: 3)> Size: 3B
array([False, True, True])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.isdecimal(), dtype=bool)
def isdigit(self) -> T_DataArray:
"""
Check whether all characters in each string are digits.
Returns
-------
isdigit : array of bool
Array of boolean values with the same shape as the original array.
Examples
--------
>>> da = xr.DataArray(["123", "1.2", "0", "CO2", "NaCl"], dims="x")
>>> da
<xarray.DataArray (x: 5)> Size: 80B
array(['123', '1.2', '0', 'CO2', 'NaCl'], dtype='<U4')
Dimensions without coordinates: x
>>> isdigit = da.str.isdigit()
>>> isdigit
<xarray.DataArray (x: 5)> Size: 5B
array([ True, False, True, False, False])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.isdigit(), dtype=bool)
def islower(self) -> T_DataArray:
"""
Check whether all characters in each string are lowercase.
Returns
-------
islower : array of bool
Array of boolean values with the same shape as the original array indicating whether all characters of each
element of the string array are lowercase (True) or not (False).
Examples
--------
>>> da = xr.DataArray(["temperature", "HUMIDITY", "pREciPiTaTioN"], dims="x")
>>> da
<xarray.DataArray (x: 3)> Size: 156B
array(['temperature', 'HUMIDITY', 'pREciPiTaTioN'], dtype='<U13')
Dimensions without coordinates: x
>>> islower = da.str.islower()
>>> islower
<xarray.DataArray (x: 3)> Size: 3B
array([ True, False, False])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.islower(), dtype=bool)
def isnumeric(self) -> T_DataArray:
"""
Check whether all characters in each string are numeric.
Returns
-------
isnumeric : array of bool
Array of boolean values with the same shape as the original array.
Examples
--------
>>> da = xr.DataArray(["123", "2.3", "H2O", "NaCl-", "Mn"], dims="x")
>>> da
<xarray.DataArray (x: 5)> Size: 100B
array(['123', '2.3', 'H2O', 'NaCl-', 'Mn'], dtype='<U5')
Dimensions without coordinates: x
>>> isnumeric = da.str.isnumeric()
>>> isnumeric
<xarray.DataArray (x: 5)> Size: 5B
array([ True, False, False, False, False])
Dimensions without coordinates: x
"""
return self._apply(func=lambda x: x.isnumeric(), dtype=bool)
def isspace(self) -> T_DataArray:
"""