-
Notifications
You must be signed in to change notification settings - Fork 589
/
functions.py
2155 lines (1820 loc) 路 59.8 KB
/
functions.py
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
import vaex.serialize
import json
import numpy as np
from vaex import column
from vaex.column import _to_string_sequence, _to_string_column, _to_string_list_sequence, _is_stringy
import re
import vaex.expression
import functools
import six
# @vaex.serialize.register_function
# class Function(FunctionSerializable):
scopes = {
'str': vaex.expression.StringOperations,
'str_pandas': vaex.expression.StringOperationsPandas,
'dt': vaex.expression.DateTime,
'td': vaex.expression.TimeDelta
}
def register_function(scope=None, as_property=False, name=None, on_expression=True):
"""Decorator to register a new function with vaex.
If on_expression is True, the function will be available as a method on an
Expression, where the first argument will be the expression itself.
Example:
>>> import vaex
>>> df = vaex.example()
>>> @vaex.register_function()
>>> def invert(x):
>>> return 1/x
>>> df.x.invert()
>>> import numpy as np
>>> df = vaex.from_arrays(departure=np.arange('2015-01-01', '2015-12-05', dtype='datetime64'))
>>> @vaex.register_function(as_property=True, scope='dt')
>>> def dt_relative_day(x):
>>> return vaex.functions.dt_dayofyear(x)/365.
>>> df.departure.dt.relative_day
"""
prefix = ''
if scope:
prefix = scope + "_"
if scope not in scopes:
raise KeyError("unknown scope")
def wrapper(f, name=name):
name = name or f.__name__
# remove possible prefix
if name.startswith(prefix):
name = name[len(prefix):]
full_name = prefix + name
if on_expression:
if scope:
def closure(name=name, full_name=full_name, function=f):
def wrapper(self, *args, **kwargs):
lazy_func = getattr(self.expression.ds.func, full_name)
args = (self.expression, ) + args
return lazy_func(*args, **kwargs)
return functools.wraps(function)(wrapper)
if as_property:
setattr(scopes[scope], name, property(closure()))
else:
setattr(scopes[scope], name, closure())
else:
def closure(name=name, full_name=full_name, function=f):
def wrapper(self, *args, **kwargs):
lazy_func = getattr(self.ds.func, full_name)
args = (self, ) + args
return lazy_func(*args, **kwargs)
return functools.wraps(function)(wrapper)
setattr(vaex.expression.Expression, name, closure())
vaex.expression.expression_namespace[prefix + name] = f
return f # we leave the original function as is
return wrapper
# name maps to numpy function
# <vaex name>:<numpy name>
numpy_function_mapping = [name.strip().split(":") if ":" in name else (name, name) for name in """
sinc
sin
cos
tan
arcsin
arccos
arctan
arctan2
sinh
cosh
tanh
arcsinh
arccosh
arctanh
log
log10
log1p
exp
expm1
sqrt
abs
where
rad2deg
deg2rad
minimum
maximum
clip
searchsorted
isfinite
""".strip().split()]
for name, numpy_name in numpy_function_mapping:
if not hasattr(np, numpy_name):
raise SystemError("numpy does not have: %s" % numpy_name)
else:
function = getattr(np, numpy_name)
def f(function=function):
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
function = f()
function.__doc__ = "Lazy wrapper around :py:data:`numpy.%s`" % name
register_function(name=name)(function)
@register_function()
def fillmissing(ar, value):
'''Returns an array where missing values are replaced by value.
See :`ismissing` for the definition of missing values.
'''
# TODO: optimize, we don't want to_numpy for strings, we want to
# do this in c++
ar = ar if not isinstance(ar, column.Column) else ar.to_numpy()
mask = ismissing(ar)
if np.any(mask):
if np.ma.isMaskedArray(ar):
ar = ar.data.copy()
else:
ar = ar.copy()
ar[mask] = value
return ar
@register_function()
def fillnan(ar, value):
'''Returns an array where nan values are replaced by value.
See :`isnan` for the definition of missing values.
'''
# TODO: optimize, we don't want to convert string to numpy
# they will never contain nan
if not _is_stringy(ar):
ar = ar if not isinstance(ar, column.Column) else ar.to_numpy()
if ar.dtype.kind in 'fO':
mask = isnan(ar)
if np.any(mask):
ar = ar.copy()
ar[mask] = value
return ar
@register_function()
def fillna(ar, value):
'''Returns an array where NA values are replaced by value.
See :`isna` for the definition of missing values.
'''
ar = ar if not isinstance(ar, column.Column) else ar.to_numpy()
mask = isna(ar)
if np.any(mask):
if np.ma.isMaskedArray(ar):
ar = ar.data.copy()
else:
ar = ar.copy()
ar[mask] = value
return ar
@register_function()
def ismissing(x):
"""Returns True where there are missing values (masked arrays), missing strings or None"""
if np.ma.isMaskedArray(x):
if x.dtype.kind in 'O':
if x.mask is not None:
return (x.data == None) | x.mask
else:
return (x.data == None)
else:
return x.mask == 1
else:
if not isinstance(x, np.ndarray) or x.dtype.kind in 'US':
x = _to_string_sequence(x)
mask = x.mask()
if mask is None:
mask = np.zeros(x.length, dtype=np.bool)
return mask
elif isinstance(x, np.ndarray) and x.dtype.kind in 'O':
return x == None
else:
return np.zeros(len(x), dtype=np.bool)
@register_function()
def notmissing(x):
return ~ismissing(x)
@register_function()
def isnan(x):
"""Returns an array where there are NaN values"""
if isinstance(x, np.ndarray):
if np.ma.isMaskedArray(x):
# we don't want a masked arrays
w = x.data != x.data
w[x.mask] = False
return w
else:
return x != x
else:
return np.zeros(len(x), dtype=np.bool)
@register_function()
def notnan(x):
return ~isnan(x)
@register_function()
def isna(x):
"""Returns a boolean expression indicating if the values are Not Availiable (missing or NaN)."""
return isnan(x) | ismissing(x)
@register_function()
def notna(x):
"""Opposite of isna"""
return ~isna(x)
########## datetime operations ##########
def _pandas_dt_fix(x):
# see https://github.com/pandas-dev/pandas/issues/23276
import pandas as pd
# not sure which version this is fixed in
if not x.flags['WRITEABLE']:
x = x.copy()
return x
@register_function(scope='dt', as_property=True)
def dt_dayofweek(x):
"""Obtain the day of the week with Monday=0 and Sunday=6
:returns: an expression containing the day of week.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.dayofweek
Expression = dt_dayofweek(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 0
1 3
2 3
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.dayofweek.values
@register_function(scope='dt', as_property=True)
def dt_dayofyear(x):
"""The ordinal day of the year.
:returns: an expression containing the ordinal day of the year.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.dayofyear
Expression = dt_dayofyear(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 285
1 42
2 316
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.dayofyear.values
@register_function(scope='dt', as_property=True)
def dt_is_leap_year(x):
"""Check whether a year is a leap year.
:returns: an expression which evaluates to True if a year is a leap year, and to False otherwise.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.is_leap_year
Expression = dt_is_leap_year(date)
Length: 3 dtype: bool (expression)
----------------------------------
0 False
1 True
2 False
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.is_leap_year.values
@register_function(scope='dt', as_property=True)
def dt_year(x):
"""Extracts the year out of a datetime sample.
:returns: an expression containing the year extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.year
Expression = dt_year(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 2009
1 2016
2 2015
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.year.values
@register_function(scope='dt', as_property=True)
def dt_month(x):
"""Extracts the month out of a datetime sample.
:returns: an expression containing the month extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.month
Expression = dt_month(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 10
1 2
2 11
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.month.values
@register_function(scope='dt', as_property=True)
def dt_month_name(x):
"""Returns the month names of a datetime sample in English.
:returns: an expression containing the month names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.month_name
Expression = dt_month_name(date)
Length: 3 dtype: str (expression)
---------------------------------
0 October
1 February
2 November
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.month_name().values.astype(str)
@register_function(scope='dt', as_property=True)
def dt_day(x):
"""Extracts the day from a datetime sample.
:returns: an expression containing the day extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.day
Expression = dt_day(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 12
1 11
2 12
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.day.values
@register_function(scope='dt', as_property=True)
def dt_day_name(x):
"""Returns the day names of a datetime sample in English.
:returns: an expression containing the day names extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.day_name
Expression = dt_day_name(date)
Length: 3 dtype: str (expression)
---------------------------------
0 Monday
1 Thursday
2 Thursday
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.day_name().values.astype(str)
@register_function(scope='dt', as_property=True)
def dt_weekofyear(x):
"""Returns the week ordinal of the year.
:returns: an expression containing the week ordinal of the year, extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.weekofyear
Expression = dt_weekofyear(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 42
1 6
2 46
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.weekofyear.values
@register_function(scope='dt', as_property=True)
def dt_hour(x):
"""Extracts the hour out of a datetime samples.
:returns: an expression containing the hour extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.hour
Expression = dt_hour(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 3
1 10
2 11
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.hour.values
@register_function(scope='dt', as_property=True)
def dt_minute(x):
"""Extracts the minute out of a datetime samples.
:returns: an expression containing the minute extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.minute
Expression = dt_minute(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 31
1 17
2 34
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.minute.values
@register_function(scope='dt', as_property=True)
def dt_second(x):
"""Extracts the second out of a datetime samples.
:returns: an expression containing the second extracted from a datetime column.
Example:
>>> import vaex
>>> import numpy as np
>>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64)
>>> df = vaex.from_arrays(date=date)
>>> df
# date
0 2009-10-12 03:31:00
1 2016-02-11 10:17:34
2 2015-11-12 11:34:22
>>> df.date.dt.second
Expression = dt_second(date)
Length: 3 dtype: int64 (expression)
-----------------------------------
0 0
1 34
2 22
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.second.values
########## timedelta operations ##########
@register_function(scope='td', as_property=True)
def td_days(x):
"""Number of days in each timedelta sample.
:returns: an expression containing the number of days in a timedelta sample.
Example:
>>> import vaex
>>> import numpy as np
>>> delta = np.array([17658720110, 11047049384039, 40712636304958, -18161254954], dtype='timedelta64[s]')
>>> df = vaex.from_arrays(delta=delta)
>>> df
# delta
0 204 days +9:12:00
1 1 days +6:41:10
2 471 days +5:03:56
3 -22 days +23:31:15
>>> df.delta.td.days
Expression = td_days(delta)
Length: 4 dtype: int64 (expression)
-----------------------------------
0 204
1 1
2 471
3 -22
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.days.values
@register_function(scope='td', as_property=True)
def td_microseconds(x):
"""Number of microseconds (>= 0 and less than 1 second) in each timedelta sample.
:returns: an expression containing the number of microseconds in a timedelta sample.
Example:
>>> import vaex
>>> import numpy as np
>>> delta = np.array([17658720110, 11047049384039, 40712636304958, -18161254954], dtype='timedelta64[s]')
>>> df = vaex.from_arrays(delta=delta)
>>> df
# delta
0 204 days +9:12:00
1 1 days +6:41:10
2 471 days +5:03:56
3 -22 days +23:31:15
>>> df.delta.td.microseconds
Expression = td_microseconds(delta)
Length: 4 dtype: int64 (expression)
-----------------------------------
0 290448
1 978582
2 19583
3 709551
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.microseconds.values
@register_function(scope='td', as_property=True)
def td_nanoseconds(x):
"""Number of nanoseconds (>= 0 and less than 1 microsecond) in each timedelta sample.
:returns: an expression containing the number of nanoseconds in a timedelta sample.
Example:
>>> import vaex
>>> import numpy as np
>>> delta = np.array([17658720110, 11047049384039, 40712636304958, -18161254954], dtype='timedelta64[s]')
>>> df = vaex.from_arrays(delta=delta)
>>> df
# delta
0 204 days +9:12:00
1 1 days +6:41:10
2 471 days +5:03:56
3 -22 days +23:31:15
>>> df.delta.td.nanoseconds
Expression = td_nanoseconds(delta)
Length: 4 dtype: int64 (expression)
-----------------------------------
0 384
1 16
2 488
3 616
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.nanoseconds.values
@register_function(scope='td', as_property=True)
def td_seconds(x):
"""Number of seconds (>= 0 and less than 1 day) in each timedelta sample.
:returns: an expression containing the number of seconds in a timedelta sample.
Example:
>>> import vaex
>>> import numpy as np
>>> delta = np.array([17658720110, 11047049384039, 40712636304958, -18161254954], dtype='timedelta64[s]')
>>> df = vaex.from_arrays(delta=delta)
>>> df
# delta
0 204 days +9:12:00
1 1 days +6:41:10
2 471 days +5:03:56
3 -22 days +23:31:15
>>> df.delta.td.seconds
Expression = td_seconds(delta)
Length: 4 dtype: int64 (expression)
-----------------------------------
0 30436
1 39086
2 28681
3 23519
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.seconds.values
@register_function(scope='td', as_property=False)
def td_total_seconds(x):
"""Total duration of each timedelta sample expressed in seconds.
:return: an expression containing the total number of seconds in a timedelta sample.
Example:
>>> import vaex
>>> import numpy as np
>>> delta = np.array([17658720110, 11047049384039, 40712636304958, -18161254954], dtype='timedelta64[s]')
>>> df = vaex.from_arrays(delta=delta)
>>> df
# delta
0 204 days +9:12:00
1 1 days +6:41:10
2 471 days +5:03:56
3 -22 days +23:31:15
>>> df.delta.td.total_seconds()
Expression = td_total_seconds(delta)
Length: 4 dtype: float64 (expression)
-------------------------------------
0 -7.88024e+08
1 -2.55032e+09
2 6.72134e+08
3 2.85489e+08
"""
import pandas as pd
return pd.Series(_pandas_dt_fix(x)).dt.total_seconds().values
########## string operations ##########
@register_function(scope='str')
def str_equals(x, y):
"""Tests if strings x and y are the same
:returns: a boolean expression
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.equals(df.text)
Expression = str_equals(text, text)
Length: 5 dtype: bool (expression)
----------------------------------
0 True
1 True
2 True
3 True
4 True
>>> df.text.str.equals('our')
Expression = str_equals(text, 'our')
Length: 5 dtype: bool (expression)
----------------------------------
0 False
1 False
2 False
3 True
4 False
"""
xmask = None
ymask = None
if not isinstance(x, six.string_types):
x = _to_string_sequence(x)
if not isinstance(y, six.string_types):
y = _to_string_sequence(y)
equals_mask = x.equals(y)
return equals_mask
@register_function(scope='str')
def str_capitalize(x):
"""Capitalize the first letter of a string sample.
:returns: an expression containing the capitalized strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.capitalize()
Expression = str_capitalize(text)
Length: 5 dtype: str (expression)
---------------------------------
0 Something
1 Very pretty
2 Is coming
3 Our
4 Way.
"""
sl = _to_string_sequence(x).capitalize()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
@register_function(scope='str')
def str_cat(x, other):
"""Concatenate two string columns on a row-by-row basis.
:param expression other: The expression of the other column to be concatenated.
:returns: an expression containing the concatenated columns.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.cat(df.text)
Expression = str_cat(text, text)
Length: 5 dtype: str (expression)
---------------------------------
0 SomethingSomething
1 very prettyvery pretty
2 is comingis coming
3 ourour
4 way.way.
"""
if isinstance(x, six.string_types):
other = _to_string_sequence(other)
sl = other.concat_reverse(x)
else:
x = _to_string_sequence(x)
if not isinstance(other, six.string_types):
other = _to_string_sequence(other)
sl = x.concat(other)
return column.ColumnStringArrow.from_string_sequence(sl)
@register_function(scope='str')
def str_center(x, width, fillchar=' '):
""" Fills the left and right side of the strings with additional characters, such that the sample has a total of `width`
characters.
:param int width: The total number of characters of the resulting string sample.
:param str fillchar: The character used for filling.
:returns: an expression containing the filled strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.center(width=11, fillchar='!')
Expression = str_center(text, width=11, fillchar='!')
Length: 5 dtype: str (expression)
---------------------------------
0 !Something!
1 very pretty
2 !is coming!
3 !!!!our!!!!
4 !!!!way.!!!
"""
sl = _to_string_sequence(x).pad(width, fillchar, True, True)
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
@register_function(scope='str')
def str_contains(x, pattern, regex=True):
"""Check if a string pattern or regex is contained within a sample of a string column.
:param str pattern: A string or regex pattern
:param bool regex: If True,
:returns: an expression which is evaluated to True if the pattern is found in a given sample, and it is False otherwise.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.contains('very')
Expression = str_contains(text, 'very')
Length: 5 dtype: bool (expression)
----------------------------------
0 False
1 True
2 False
3 False
4 False
"""
return _to_string_sequence(x).search(pattern, regex)
# TODO: default regex is False, which breaks with pandas
@register_function(scope='str')
def str_count(x, pat, regex=False):
"""Count the occurences of a pattern in sample of a string column.
:param str pat: A string or regex pattern
:param bool regex: If True,
:returns: an expression containing the number of times a pattern is found in each sample.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.count(pat="et", regex=False)
Expression = str_count(text, pat='et', regex=False)
Length: 5 dtype: int64 (expression)
-----------------------------------
0 1
1 1
2 0
3 0
4 0
"""
return _to_string_sequence(x).count(pat, regex)
# TODO: what to do with decode and encode
@register_function(scope='str')
def str_endswith(x, pat):
"""Check if the end of each string sample matches the specified pattern.
:param str pat: A string pattern or a regex
:returns: an expression evaluated to True if the pattern is found at the end of a given sample, False otherwise.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our