Repository navigation
Expand file tree
/
Copy patharray.py
More file actions
9628 lines (8270 loc) · 329 KB
/
Copy patharray.py
File metadata and controls
9628 lines (8270 loc) · 329 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
# -*- coding: utf8 -*-
from __future__ import absolute_import, division, print_function
"""
Matrix class
"""
# ? implement multi group in one axis getitem: lipro['P01,P02;P05'] <=> (lipro['P01,P02'], lipro['P05'])
# * we need an API to get to the "next" label. Sometimes, we want to use label+1, but that is problematic when labels
# are not numeric, or have not a step of 1.
# X.agegroup[X.agegroup.after(25):]
# X.agegroup[X.agegroup[25].next():]
# * implement keepaxes=True for _group_aggregate instead of/in addition to group tuples
# ? implement newaxis
# * Axis.sequence? geo.seq('A31', 'A38') (equivalent to geo['A31..A38'])
# ? re-implement row_totals/col_totals? or what do we do with them?
# * time specific API so that we know if we go for a subclass or not
# * data alignment in arithmetic methods
# * test structured arrays
# * use larray "utils" in LIAM2 (to avoid duplicated code)
from collections import Iterable, Sequence, OrderedDict
from itertools import product, chain, groupby, islice, repeat
import os
import sys
import functools
import warnings
try:
import builtins
except ImportError:
import __builtin__ as builtins
import numpy as np
import pandas as pd
try:
import xlwings as xw
except ImportError:
xw = None
try:
from numpy import nanprod as np_nanprod
except ImportError:
np_nanprod = None
from larray.core.abstractbases import ABCLArray
from larray.core.constants import nan
from larray.core.metadata import Metadata
from larray.core.expr import ExprNode
from larray.core.ufuncs import SupportsNumpyUfuncs
from larray.core.group import (Group, IGroup, LGroup, remove_nested_groups, _to_key, _to_keys,
_translate_sheet_name, _translate_group_key_hdf)
from larray.core.axis import Axis, AxisReference, AxisCollection, X, _make_axis
from larray.util.misc import (table2str, size2str, basestring, izip, rproduct, ReprString, duplicates,
float_error_handler_factory, _isnoneslice, light_product, unique_list, common_type,
renamed_to, deprecate_kwarg, LHDFStore, lazy_attribute, unique_multi, SequenceZip,
Repeater, Product, ensure_no_numpy_type, PY2)
from larray.util.options import _OPTIONS, DISPLAY_MAXLINES, DISPLAY_EDGEITEMS, DISPLAY_WIDTH, DISPLAY_PRECISION
def all(values, axis=None):
r"""
Test whether all array elements along a given axis evaluate to True.
See Also
--------
LArray.all
"""
if isinstance(values, LArray):
return values.all(axis)
else:
return builtins.all(values)
def any(values, axis=None):
r"""
Test whether any array elements along a given axis evaluate to True.
See Also
--------
LArray.any
"""
if isinstance(values, LArray):
return values.any(axis)
else:
return builtins.any(values)
# commutative modulo float precision errors
def sum(array, *args, **kwargs):
r"""
Sum of array elements.
See Also
--------
LArray.sum
"""
# XXX: we might want to be more aggressive here (more types to convert), however, generators should still be
# computed via the builtin.
if isinstance(array, (np.ndarray, list)):
array = LArray(array)
if isinstance(array, LArray):
return array.sum(*args, **kwargs)
else:
return builtins.sum(array, *args, **kwargs)
def prod(array, *args, **kwargs):
r"""
Product of array elements.
See Also
--------
LArray.prod
"""
return array.prod(*args, **kwargs)
def cumsum(array, *args, **kwargs):
r"""
Returns the cumulative sum of array elements.
See Also
--------
LArray.cumsum
"""
return array.cumsum(*args, **kwargs)
def cumprod(array, *args, **kwargs):
r"""
Returns the cumulative product of array elements.
See Also
--------
LArray.cumprod
"""
return array.cumprod(*args, **kwargs)
def min(array, *args, **kwargs):
r"""
Minimum of array elements.
See Also
--------
LArray.min
"""
if isinstance(array, LArray):
return array.min(*args, **kwargs)
else:
return builtins.min(array, *args, **kwargs)
def max(array, *args, **kwargs):
r"""
Maximum of array elements.
See Also
--------
LArray.max
"""
if isinstance(array, LArray):
return array.max(*args, **kwargs)
else:
return builtins.max(array, *args, **kwargs)
def mean(array, *args, **kwargs):
r"""
Computes the arithmetic mean.
See Also
--------
LArray.mean
"""
return array.mean(*args, **kwargs)
def median(array, *args, **kwargs):
r"""
Computes the median.
See Also
--------
LArray.median
"""
return array.median(*args, **kwargs)
def percentile(array, *args, **kwargs):
r"""
Computes the qth percentile of the data along the specified axis.
See Also
--------
LArray.percentile
"""
return array.percentile(*args, **kwargs)
# not commutative
def ptp(array, *args, **kwargs):
r"""
Returns the range of values (maximum - minimum).
See Also
--------
LArray.ptp
"""
return array.ptp(*args, **kwargs)
def var(array, *args, **kwargs):
r"""
Computes the variance.
See Also
--------
LArray.var
"""
return array.var(*args, **kwargs)
def std(array, *args, **kwargs):
r"""
Computes the standard deviation.
See Also
--------
LArray.std
"""
return array.std(*args, **kwargs)
def concat(arrays, axis=0, dtype=None):
r"""Concatenate arrays along axis
Parameters
----------
arrays : tuple of LArray
Arrays to concatenate.
axis : axis reference (int, str or Axis), optional
Axis along which to concatenate. All arrays must have that axis. Defaults to the first axis.
dtype : dtype, optional
Result data type. Defaults to the "closest" type which can hold all arrays types without loss of information.
Returns
-------
LArray
Examples
--------
>>> arr1 = ndtest((2, 3))
>>> arr1
a\b b0 b1 b2
a0 0 1 2
a1 3 4 5
>>> arr2 = ndtest('a=a0,a1;b=b3')
>>> arr2
a\b b3
a0 0
a1 1
>>> arr3 = ndtest('b=b4,b5')
>>> arr3
b b4 b5
0 1
>>> concat((arr1, arr2, arr3), 'b')
a\b b0 b1 b2 b3 b4 b5
a0 0 1 2 0 0 1
a1 3 4 5 1 0 1
"""
# Get axis by name, so that we do *NOT* check they are "compatible", because it makes sense to append axes of
# different length
name = arrays[0].axes[axis].name
arrays_labels = [array.axes[axis].labels for array in arrays]
# switch to object dtype if labels are of incompatible types, so that we do not implicitly convert numeric types to
# strings (numpy should not do this in the first place but that is another story). This can happen for example when
# we want to add a "total" tick to a numeric axis (eg age).
labels_type = common_type(arrays_labels)
if labels_type is object:
# astype always copies, while asarray only copies if necessary
arrays_labels = [np.asarray(labels, dtype=object) for labels in arrays_labels]
combined_axis = Axis(np.concatenate(arrays_labels), name)
# combine all axes (using labels from any side if any)
result_axes = arrays[0].axes.replace(axis, combined_axis).union(*[array.axes - axis for array in arrays[1:]])
if dtype is None:
dtype = common_type(arrays)
result = empty(result_axes, dtype=dtype)
start = 0
for labels, array in zip(arrays_labels, arrays):
stop = start + len(labels)
result[combined_axis.i[start:stop]] = array
start = stop
return result
if PY2:
class LArrayIterator(object):
__slots__ = ('next',)
def __init__(self, array):
data_iter = iter(array.data)
next_data_func = data_iter.next
res_axes = array.axes[1:]
# this case should not happen (handled by the fastpath in LArray.__iter__)
assert len(res_axes) > 0
def next_func():
return LArray(next_data_func(), res_axes)
self.next = next_func
def __iter__(self):
return self
else:
class LArrayIterator(object):
__slots__ = ('__next__',)
def __init__(self, array):
data_iter = iter(array.data)
next_data_func = data_iter.__next__
res_axes = array.axes[1:]
# this case should not happen (handled by the fastpath in LArray.__iter__)
assert len(res_axes) > 0
def next_func():
return LArray(next_data_func(), res_axes)
self.__next__ = next_func
def __iter__(self):
return self
# TODO: rename to LArrayIndexIndexer or something like that
class LArrayPositionalIndexer(object):
"""
equivalent to numpy indexing when indexing along a single axis *but* indexes the cross product of multiple axes
instead of points
"""
__slots__ = ('array',)
def __init__(self, array):
self.array = array
def _translate_key(self, key):
r"""
Translates key into tuple of IGroup, i.e.
tuple of collections of labels.
"""
if not isinstance(key, tuple):
key = (key,)
if len(key) > self.array.ndim:
raise IndexError("key has too many indices (%d) for array with %d dimensions" % (len(key), self.array.ndim))
# no need to create a full nd key as that will be done later anyway
return tuple(axis.i[axis_key]
for axis_key, axis in zip(key, self.array.axes))
def __getitem__(self, key):
ndim = self.array.ndim
full_scalar_key = (
(isinstance(key, (int, np.integer)) and ndim == 1) or
(isinstance(key, tuple) and len(key) == ndim and all(isinstance(k, (int, np.integer)) for k in key))
)
# fast path when the result is a scalar
if full_scalar_key:
return self.array.data[key]
else:
return self.array[self._translate_key(key)]
def __setitem__(self, key, value):
array = self.array
ndim = array.ndim
full_scalar_key = (
(isinstance(key, (int, np.integer)) and ndim == 1) or
(isinstance(key, tuple) and len(key) == ndim and all(isinstance(k, (int, np.integer)) for k in key))
)
# fast path when setting a single cell
if full_scalar_key:
array.data[key] = value
else:
array[self._translate_key(key)] = value
def __len__(self):
return len(self.array)
def __iter__(self):
array = self.array
# fast path for 1D arrays (where we return scalars)
if array.ndim <= 1:
return iter(array.data)
else:
return LArrayIterator(array)
class LArrayPointsIndexer(object):
__slots__ = ('array',)
def __init__(self, array):
self.array = array
def _prepare_key(self, key, wildcard=False):
axes = self.array.axes
# 1) complete key & translate (those two cannot be dissociated because to complete
# the key we need to know which axis each key belongs to and to do that, we need to
# translate the key to indices)
translated_key = axes._translated_key(key)
# 2) transform keys to IGroup and non-LArray advanced keys to LArray with a combined axis
return axes._adv_keys_to_combined_axis_la_keys(translated_key, wildcard)
def __getitem__(self, key):
return self.array.__getitem__(self._prepare_key(key), translate_key=False)
def __setitem__(self, key, value):
self.array.__setitem__(self._prepare_key(key, wildcard=True), value, translate_key=False)
# TODO: add support for slices
# To select the first 4 values across all axes:
#
# >>> arr.iflat[:4]
# a_b a0_b0 a0_b1 a0_b2 a1_b0
# 0 10 20 30
class LArrayFlatIndicesIndexer(object):
r"""
Access the array by index as if it was flat (one dimensional) and all its axes were combined.
Notes
-----
In general arr.iflat[key] should be equivalent to (but much faster than) arr.combine_axes().i[key]
Examples
--------
>>> arr = ndtest((2, 3)) * 10
>>> arr
a\b b0 b1 b2
a0 0 10 20
a1 30 40 50
To select the first, second, fourth and fifth values across all axes:
>>> arr.combine_axes().i[[0, 1, 3, 4]]
a_b a0_b0 a0_b1 a1_b0 a1_b1
0 10 30 40
>>> arr.iflat[[0, 1, 3, 4]]
a_b a0_b0 a0_b1 a1_b0 a1_b1
0 10 30 40
Set the first and sixth values to 42
>>> arr.iflat[[0, 5]] = 42
>>> arr
a\b b0 b1 b2
a0 42 10 20
a1 30 40 42
When the key is an LArray, the result will have the axes of the key
>>> key = LArray([0, 3], 'c=c0,c1')
>>> key
c c0 c1
0 3
>>> arr.iflat[key]
c c0 c1
42 30
"""
__slots__ = ('array',)
def __init__(self, array):
self.array = array
def __getitem__(self, flat_key, sep='_'):
if isinstance(flat_key, ABCLArray):
flat_np_key = flat_key.data
res_axes = flat_key.axes
else:
flat_np_key = np.asarray(flat_key)
axes = self.array.axes
nd_key = np.unravel_index(flat_np_key, axes.shape)
# the following lines are equivalent to (but faster than) "return array.ipoints[nd_key]"
# TODO: extract a function which only computes the combined axes because we do not use the actual LArrays
# produced here, which is wasteful. AxisCollection._flat_lookup seems related (but not usable as-is).
la_key = axes._adv_keys_to_combined_axis_la_keys(nd_key, sep=sep)
first_axis_key_axes = la_key[0].axes
assert all(isinstance(axis_key, ABCLArray) and axis_key.axes is first_axis_key_axes
for axis_key in la_key[1:])
res_axes = first_axis_key_axes
return LArray(self.array.data.flat[flat_np_key], res_axes)
def __setitem__(self, flat_key, value):
# np.ndarray.flat is a flatiter object but it is indexable despite the name
self.array.data.flat[flat_key] = value
def __len__(self):
return self.array.size
# TODO: rename to LArrayIndexPointsIndexer or something like that
class LArrayPositionalPointsIndexer(object):
__slots__ = ('array',)
"""
the closest to numpy indexing we get, but not 100% the same.
"""
def __init__(self, array):
self.array = array
def _prepare_key(self, key, wildcard=False):
return self.array.axes._adv_keys_to_combined_axis_la_keys(key, wildcard)
def __getitem__(self, key):
return self.array.__getitem__(self._prepare_key(key), translate_key=False)
def __setitem__(self, key, value):
# we still need to prepare the key instead of letting numpy handle everything so that
# existing (integer)LArray keys are broadcasted correctly (using axes names).
self.array.__setitem__(self._prepare_key(key, wildcard=True), value, translate_key=False)
def get_axis(obj, i):
r"""
Returns an axis according to its position.
Parameters
----------
obj : LArray or other array
Input LArray or any array object which has a shape attribute (NumPy or Pandas array).
i : int
index of the axis.
Returns
-------
Axis
Axis corresponding to the given index if input `obj` is a LArray. A new anonymous Axis with the length of
the ith dimension of the input `obj` otherwise.
Examples
--------
>>> arr = ndtest((2, 2, 2))
>>> arr
a b\c c0 c1
a0 b0 0 1
a0 b1 2 3
a1 b0 4 5
a1 b1 6 7
>>> get_axis(arr, 1)
Axis(['b0', 'b1'], 'b')
>>> np_arr = np.zeros((2, 2, 2))
>>> get_axis(np_arr, 1)
Axis(2, None)
"""
return obj.axes[i] if isinstance(obj, LArray) else Axis(obj.shape[i])
_arg_agg = {
'q': """
q : int in range of [0,100] (or sequence of floats)
Percentile to compute, which must be between 0 and 100 inclusive."""
}
_kwarg_agg = {
'dtype': {'value': None, 'doc': """
dtype : dtype, optional
The data type of the returned array. Defaults to None (the dtype of the input array)."""},
'out': {'value': None, 'doc': """
out : LArray, optional
Alternate output array in which to place the result. It must have the same shape as the expected output and
its type is preserved (e.g., if dtype(out) is float, the result will consist of 0.0’s and 1.0’s).
Axes and labels can be different, only the shape matters. Defaults to None (create a new array)."""},
'ddof': {'value': 1, 'doc': """
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in the calculation is ``N - ddof``, where ``N`` represents
the number of elements. Defaults to 1."""},
'skipna': {'value': None, 'doc': """
skipna : bool, optional
Whether or not to skip NaN (null) values. If False, resulting cells will be NaN if any of the aggregated
cells is NaN. Defaults to True."""},
'keepaxes': {'value': False, 'doc': """
keepaxes : bool or label-like, optional
Whether or not reduced axes are left in the result as dimensions with size one.
If True, reduced axes will contain a unique label representing the applied aggregation
(e.g. 'sum', 'prod', ...). It is possible to override this label by passing a specific value
(e.g. keepaxes='summation'). Defaults to False."""},
'interpolation': {'value': 'linear', 'doc': """
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}, optional
Interpolation method to use when the desired quantile lies between two data points ``i < j``:
* linear: ``i + (j - i) * fraction``, where ``fraction`` is the fractional part of the index surrounded
by ``i`` and ``j``.
* lower: ``i``.
* higher: ``j``.
* nearest: ``i`` or ``j``, whichever is nearest.
* midpoint: ``(i + j) / 2``.
Defaults to 'linear'."""}
}
def _doc_agg_method(func, by=False, long_name='', action_verb='perform', extra_args=[], kwargs=[]):
if not long_name:
long_name = func.__name__
_args = ','.join(extra_args) + ', ' if len(extra_args) > 0 else ''
_kwargs = ', '.join(["{}={!r}".format(k, _kwarg_agg[k]['value']) for k in kwargs]) + ', ' if len(kwargs) > 0 else ''
signature = '{name}({args}*axes_and_groups, {kwargs}**explicit_axes)'.format(name=func.__name__,
args=_args, kwargs=_kwargs)
if by:
specific_template = """The {long_name} is {action_verb}ed along all axes except the given one(s).
For groups, {long_name} is {action_verb}ed along groups and non associated axes."""
else:
specific_template = "Axis(es) or group(s) along which the {long_name} is {action_verb}ed."
doc_specific = specific_template.format(long_name=long_name, action_verb=action_verb)
doc_args = "".join(_arg_agg[arg] for arg in extra_args)
doc_kwargs = "".join(_kwarg_agg[kw]['doc'] for kw in kwargs)
doc_varargs = r"""
\*axes_and_groups : None or int or str or Axis or Group or any combination of those
{specific}
The default (no axis or group) is to {action_verb} the {long_name} over all the dimensions of the input
array.
An axis can be referred by:
* its index (integer). Index can be a negative integer, in which case it counts from the last to the
first axis.
* its name (str or AxisReference). You can use either a simple string ('axis_name') or the special
variable X (X.axis_name).
* a variable (Axis). If the axis has been defined previously and assigned to a variable, you can pass it as
argument.
You may not want to {action_verb} the {long_name} over a whole axis but over a selection of specific
labels. To do so, you have several possibilities:
* (['a1', 'a3', 'a5'], 'b1, b3, b5') : labels separated by commas in a list or a string
* ('a1:a5:2') : select labels using a slice (general syntax is 'start:end:step' where is 'step' is
optional and 1 by default).
* (a='a1, a2, a3', X.b['b1, b2, b3']) : in case of possible ambiguity, i.e. if labels can belong to more
than one axis, you must precise the axis.
* ('a1:a3; a5:a7', b='b0,b2; b1,b3') : create several groups with semicolons.
Names are simply given by the concatenation of labels (here: 'a1,a2,a3', 'a5,a6,a7', 'b0,b2' and 'b1,b3')
* ('a1:a3 >> a123', 'b[b0,b2] >> b12') : operator ' >> ' allows to rename groups."""\
.format(specific=doc_specific, action_verb=action_verb, long_name=long_name)
parameters = """Parameters
----------{args}{varargs}{kwargs}""".format(args=doc_args, varargs=doc_varargs, kwargs=doc_kwargs)
func.__doc__ = func.__doc__.format(signature=signature, parameters=parameters)
_always_return_float = {np.mean, np.nanmean, np.median, np.nanmedian, np.percentile, np.nanpercentile,
np.std, np.nanstd, np.var, np.nanvar}
obj_isnan = np.vectorize(lambda x: x != x, otypes=[bool])
def element_equal(a1, a2, rtol=0, atol=0, nan_equals=False):
import warnings
warnings.warn("element_equal() is deprecated. Use array1.eq(array2, rtol, atol, nan_equals) instead.",
FutureWarning, stacklevel=2)
a1 = aslarray(a1)
return a1.eq(a2, rtol, atol, nan_equals)
def nan_equal(a1, a2):
import warnings
warnings.warn("nan_equal() is deprecated. Use array1.eq(array2, nans_equal=True) instead.",
FutureWarning, stacklevel=2)
return a1.eq(a2, nans_equal=True)
def _handle_meta(meta, title):
"""
Make sure meta is either None or a Metadata instance
"""
if title is not None:
if meta is None:
meta = Metadata()
warnings.warn("title argument is deprecated. Please use meta argument instead", FutureWarning, stacklevel=2)
meta['title'] = title
if meta is None or isinstance(meta, Metadata):
return meta
# XXX: move this test in Metadata.__init__?
if not isinstance(meta, (list, dict, OrderedDict)):
raise TypeError("Expected None, list of pairs, dict, OrderedDict or Metadata object "
"instead of {}".format(type(meta).__name__))
return Metadata(meta)
class LArray(ABCLArray, SupportsNumpyUfuncs):
r"""
A LArray object represents a multidimensional, homogeneous array of fixed-size items with labeled axes.
The function :func:`aslarray` can be used to convert a NumPy array or Pandas DataFrame into a LArray.
Parameters
----------
data : scalar, tuple, list or NumPy ndarray
Input data.
axes : collection (tuple, list or AxisCollection) of axes (int, str or Axis), optional
Axes.
title : str, optional
Deprecated. See 'meta' below.
meta : list of pairs or dict or OrderedDict or Metadata, optional
Metadata (title, description, author, creation_date, ...) associated with the array.
Keys must be strings. Values must be of type string, int, float, date, time or datetime.
dtype : type, optional
Datatype for the array. Defaults to None (inferred from the data).
Attributes
----------
data : NumPy ndarray
Data.
axes : AxisCollection
Axes.
meta : Metadata
Metadata (title, description, author, creation_date, ...) associated with the array.
See Also
--------
sequence : Create a LArray by sequentially applying modifications to the array along axis.
ndtest : Create a test LArray with increasing elements.
zeros : Create a LArray, each element of which is zero.
ones : Create a LArray, each element of which is 1.
full : Create a LArray filled with a given value.
empty : Create a LArray, but leave its allocated memory unchanged (i.e., it contains “garbage”).
Warnings
--------
Metadata is not kept when actions or methods are applied on an array
except for operations modifying the object in-place, such as: `pop[age < 10] = 0`.
Do not add metadata to an array if you know you will apply actions or methods
on it before dumping it.
Examples
--------
>>> age = Axis([10, 11, 12], 'age')
>>> sex = Axis('sex=M,F')
>>> time = Axis([2007, 2008, 2009], 'time')
>>> axes = [age, sex, time]
>>> data = np.zeros((len(axes), len(sex), len(time)))
>>> LArray(data, axes)
age sex\time 2007 2008 2009
10 M 0.0 0.0 0.0
10 F 0.0 0.0 0.0
11 M 0.0 0.0 0.0
11 F 0.0 0.0 0.0
12 M 0.0 0.0 0.0
12 F 0.0 0.0 0.0
>>> # with metadata (Python <= 3.5)
>>> arr = LArray(data, axes, meta=[('title', 'my title'), ('author', 'John Smith')])
>>> # with metadata (Python 3.6+)
>>> arr = LArray(data, axes, meta=Metadata(title='my title', author='John Smith')) # doctest: +SKIP
Array creation functions
>>> full(axes, 10.0)
age sex\time 2007 2008 2009
10 M 10.0 10.0 10.0
10 F 10.0 10.0 10.0
11 M 10.0 10.0 10.0
11 F 10.0 10.0 10.0
12 M 10.0 10.0 10.0
12 F 10.0 10.0 10.0
>>> arr = empty(axes)
>>> arr['F'] = 1.0
>>> arr['M'] = -1.0
>>> arr
age sex\time 2007 2008 2009
10 M -1.0 -1.0 -1.0
10 F 1.0 1.0 1.0
11 M -1.0 -1.0 -1.0
11 F 1.0 1.0 1.0
12 M -1.0 -1.0 -1.0
12 F 1.0 1.0 1.0
>>> bysex = sequence(sex, initial=-1, inc=2)
>>> bysex
sex M F
-1 1
>>> sequence(age, initial=10, inc=bysex)
sex\age 10 11 12
M 10 9 8
F 10 11 12
"""
__slots__ = ('data', 'axes', '_meta')
def __init__(self, data, axes=None, title=None, meta=None, dtype=None):
data = np.asarray(data, dtype=dtype)
ndim = data.ndim
if axes is None:
axes = AxisCollection(data.shape)
else:
if not isinstance(axes, AxisCollection):
axes = AxisCollection(axes)
if axes.ndim != ndim:
raise ValueError("number of axes (%d) does not match "
"number of dimensions of data (%d)"
% (axes.ndim, ndim))
if axes.shape != data.shape:
raise ValueError("length of axes %s does not match "
"data shape %s" % (axes.shape, data.shape))
self.data = data
self.axes = axes
meta = _handle_meta(meta, title)
self._meta = meta
@property
def title(self):
import warnings
warnings.warn("title attribute is deprecated. Please use meta.title instead", FutureWarning, stacklevel=2)
return self._meta.title if self._meta is not None and 'title' in self._meta else None
@title.setter
def title(self, title):
import warnings
warnings.warn("title attribute is deprecated. Please use meta.title instead", FutureWarning, stacklevel=2)
if not isinstance(title, basestring):
raise TypeError("Expected string value, got {}".format(type(title).__name__))
self._meta.title = title
@property
def meta(self):
r"""Returns metadata of the array.
Returns
-------
Metadata:
Metadata of the array.
"""
if self._meta is None:
self._meta = Metadata()
return self._meta
@meta.setter
def meta(self, meta):
self._meta = _handle_meta(meta, None)
# TODO: rename to inonzero and implement a label version of nonzero
# TODO: implement wildcard argument to avoid producing the combined labels
def nonzero(self):
r"""
Returns the indices of the elements that are non-zero.
Specifically, it returns a tuple of arrays (one for each dimension)
containing the indices of the non-zero elements in that dimension.
Returns
-------
tuple of arrays : tuple
Indices of elements that are non-zero.
Examples
--------
>>> arr = ndtest((2, 3))
>>> arr
a\b b0 b1 b2
a0 0 1 2
a1 3 4 5
>>> cond = arr > 1
>>> cond
a\b b0 b1 b2
a0 False False True
a1 True True True
>>> a, b = cond.nonzero()
>>> a
a.i[a_b a0_b2 a1_b0 a1_b1 a1_b2
0 1 1 1]
>>> b
b.i[a_b a0_b2 a1_b0 a1_b1 a1_b2
2 0 1 2]
>>> # equivalent to arr[cond]
>>> arr[cond.nonzero()]
a_b a0_b2 a1_b0 a1_b1 a1_b2
2 3 4 5
"""
# the next step will be to return a Grid instead so that cond.nonzero() *displays*
# (however it is stored!) as something like:
# option a)
# a_b a0_b2 a1_b0 a1_b1 a1_b2
# a0,b2 a1,b0 a1,b1 a1,b2
# PRO: * result axes are the same as grid axes
# CON: * does not support getting the indexing for one axis (or at least it does not make it obvious that it
# is supported)
# * in the case of ambiguous labels (same label on several axes), this is not explicit enough
# OR
# option b)
# source_axis\a_b a0_b2 a1_b0 a1_b1 a1_b2
# a a0 a1 a1 a1
# b b2 b0 b1 b2
# in the presence of duplicate labels on the same axis (e.g. assuming we replace 'b2' by a duplicate 'b1' label)
# source_axis\a_b a0_b1#1 a1_b0 a1_b1#0 a1_b1#1
# a a0 a1 a1 a1
# b b1#1 b0 b1#0 b1#1
# OR
# option c)
# a_b\source_axis a b
# a0_b2 a0 b2
# a1_b0 a1 b0
# a1_b1 a1 b1
# a1_b2 a1 b2
# Notes
# -----
# dtypes of a and b column can be different but since we probably only store indices, we will not even need
# an LFrame so this shouldn't be a problem.
ikey = self.data.nonzero()
la_key = self.axes._adv_keys_to_combined_axis_la_keys(ikey)
return tuple(IGroup(axis_key, axis=axis) for axis_key, axis in zip(la_key, self.axes))
def set_axes(self, axes_to_replace=None, new_axis=None, inplace=False, **kwargs):
r"""
Replace one, several or all axes of the array.
Parameters
----------
axes_to_replace : axis ref or dict {axis ref: axis} or list of tuple (axis ref, axis) \
or list of Axis or AxisCollection
Axes to replace. If a single axis reference is given, the `new_axis` argument must be provided.
If a list of Axis or an AxisCollection is given, all axes will be replaced by the new ones.
In that case, the number of new axes must match the number of the old ones.
new_axis : Axis, optional
New axis if `axes_to_replace` contains a single axis reference.
inplace : bool, optional
Whether or not to modify the original object or return a new array and leave the original intact.
Defaults to False.
**kwargs : Axis
New axis for each axis to replace given as a keyword argument.
Returns
-------
LArray
Array with axes replaced.
See Also
--------
rename : rename one of several axes
Examples
--------
>>> arr = ndtest((2, 3))
>>> arr
a\b b0 b1 b2
a0 0 1 2
a1 3 4 5
>>> row = Axis(['r0', 'r1'], 'row')
>>> column = Axis(['c0', 'c1', 'c2'], 'column')
Replace one axis (second argument `new_axis` must be provided)
>>> arr.set_axes('a', row)
row\b b0 b1 b2
r0 0 1 2
r1 3 4 5
Replace several axes (keywords, list of tuple or dictionary)
>>> arr.set_axes(a=row, b=column) # doctest: +SKIP
>>> # or
>>> arr.set_axes([('a', row), ('b', column)]) # doctest: +SKIP
>>> # or
>>> arr.set_axes({'a': row, 'b': column})
row\column c0 c1 c2
r0 0 1 2
r1 3 4 5
Replace all axes (list of axes or AxisCollection)
>>> arr.set_axes([row, column])
row\column c0 c1 c2
r0 0 1 2
r1 3 4 5
>>> arr2 = ndtest([row, column])