-
Notifications
You must be signed in to change notification settings - Fork 28k
/
types.py
1338 lines (1130 loc) · 48.6 KB
/
types.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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Type-specific codes between pandas and PyArrow. Also contains some utils to correct
pandas instances during the type conversion.
"""
import datetime
import itertools
from typing import Any, Callable, Iterable, List, Optional, Union, TYPE_CHECKING
from pyspark.sql.types import (
cast,
BooleanType,
ByteType,
ShortType,
IntegerType,
IntegralType,
LongType,
FloatType,
DoubleType,
DecimalType,
StringType,
BinaryType,
DateType,
TimestampType,
TimestampNTZType,
DayTimeIntervalType,
ArrayType,
MapType,
StructType,
StructField,
NullType,
DataType,
UserDefinedType,
VariantType,
VariantVal,
_create_row,
)
from pyspark.errors import PySparkTypeError, UnsupportedOperationException, PySparkValueError
from pyspark.loose_version import LooseVersion
if TYPE_CHECKING:
import pandas as pd
import pyarrow as pa
from pyspark.sql.pandas._typing import SeriesLike as PandasSeriesLike
def to_arrow_type(
dt: DataType,
error_on_duplicated_field_names_in_struct: bool = False,
timestamp_utc: bool = True,
) -> "pa.DataType":
"""
Convert Spark data type to PyArrow type
Parameters
----------
dt : :class:`DataType`
The Spark data type.
error_on_duplicated_field_names_in_struct: bool, default False
Whether to raise an exception when there are duplicated field names in a
:class:`pyspark.sql.types.StructType`. (default ``False``)
timestamp_utc : bool, default True
If ``True`` (the default), :class:`TimestampType` is converted to a timezone-aware
:class:`pyarrow.TimestampType` with UTC as the timezone. If ``False``,
:class:`TimestampType` is converted to a timezone-naive :class:`pyarrow.TimestampType`.
The JVM expects timezone-aware timestamps to be in UTC. Always keep this set to ``True``
except in special cases, such as when this function is used in a test.
Returns
-------
:class:`pyarrow.DataType`
"""
import pyarrow as pa
if type(dt) == BooleanType:
arrow_type = pa.bool_()
elif type(dt) == ByteType:
arrow_type = pa.int8()
elif type(dt) == ShortType:
arrow_type = pa.int16()
elif type(dt) == IntegerType:
arrow_type = pa.int32()
elif type(dt) == LongType:
arrow_type = pa.int64()
elif type(dt) == FloatType:
arrow_type = pa.float32()
elif type(dt) == DoubleType:
arrow_type = pa.float64()
elif type(dt) == DecimalType:
arrow_type = pa.decimal128(dt.precision, dt.scale)
elif type(dt) == StringType:
arrow_type = pa.string()
elif type(dt) == BinaryType:
arrow_type = pa.binary()
elif type(dt) == DateType:
arrow_type = pa.date32()
elif type(dt) == TimestampType and timestamp_utc:
# Timestamps should be in UTC, JVM Arrow timestamps require a timezone to be read
arrow_type = pa.timestamp("us", tz="UTC")
elif type(dt) == TimestampType:
arrow_type = pa.timestamp("us", tz=None)
elif type(dt) == TimestampNTZType:
arrow_type = pa.timestamp("us", tz=None)
elif type(dt) == DayTimeIntervalType:
arrow_type = pa.duration("us")
elif type(dt) == ArrayType:
field = pa.field(
"element",
to_arrow_type(dt.elementType, error_on_duplicated_field_names_in_struct, timestamp_utc),
nullable=dt.containsNull,
)
arrow_type = pa.list_(field)
elif type(dt) == MapType:
key_field = pa.field(
"key",
to_arrow_type(dt.keyType, error_on_duplicated_field_names_in_struct, timestamp_utc),
nullable=False,
)
value_field = pa.field(
"value",
to_arrow_type(dt.valueType, error_on_duplicated_field_names_in_struct, timestamp_utc),
nullable=dt.valueContainsNull,
)
arrow_type = pa.map_(key_field, value_field)
elif type(dt) == StructType:
field_names = dt.names
if error_on_duplicated_field_names_in_struct and len(set(field_names)) != len(field_names):
raise UnsupportedOperationException(
error_class="DUPLICATED_FIELD_NAME_IN_ARROW_STRUCT",
message_parameters={"field_names": str(field_names)},
)
fields = [
pa.field(
field.name,
to_arrow_type(
field.dataType, error_on_duplicated_field_names_in_struct, timestamp_utc
),
nullable=field.nullable,
)
for field in dt
]
arrow_type = pa.struct(fields)
elif type(dt) == NullType:
arrow_type = pa.null()
elif isinstance(dt, UserDefinedType):
arrow_type = to_arrow_type(
dt.sqlType(), error_on_duplicated_field_names_in_struct, timestamp_utc
)
elif type(dt) == VariantType:
fields = [
pa.field("value", pa.binary(), nullable=False),
pa.field("metadata", pa.binary(), nullable=False),
]
arrow_type = pa.struct(fields)
else:
raise PySparkTypeError(
error_class="UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION",
message_parameters={"data_type": str(dt)},
)
return arrow_type
def to_arrow_schema(
schema: StructType,
error_on_duplicated_field_names_in_struct: bool = False,
timestamp_utc: bool = True,
) -> "pa.Schema":
"""
Convert a schema from Spark to Arrow
Parameters
----------
schema : :class:`StructType`
The Spark schema.
error_on_duplicated_field_names_in_struct: bool, default False
Whether to raise an exception when there are duplicated field names in an inner
:class:`pyspark.sql.types.StructType`. (default ``False``)
timestamp_utc : bool, default True
If ``True`` (the default), :class:`TimestampType` is converted to a timezone-aware
:class:`pyarrow.TimestampType` with UTC as the timezone. If ``False``,
:class:`TimestampType` is converted to a timezone-naive :class:`pyarrow.TimestampType`.
The JVM expects timezone-aware timestamps to be in UTC. Always keep this set to ``True``
except in special cases, such as when this function is used in a test
Returns
-------
:class:`pyarrow.Schema`
"""
import pyarrow as pa
fields = [
pa.field(
field.name,
to_arrow_type(field.dataType, error_on_duplicated_field_names_in_struct, timestamp_utc),
nullable=field.nullable,
)
for field in schema
]
return pa.schema(fields)
def from_arrow_type(at: "pa.DataType", prefer_timestamp_ntz: bool = False) -> DataType:
"""Convert pyarrow type to Spark data type."""
import pyarrow.types as types
spark_type: DataType
if types.is_boolean(at):
spark_type = BooleanType()
elif types.is_int8(at):
spark_type = ByteType()
elif types.is_int16(at):
spark_type = ShortType()
elif types.is_int32(at):
spark_type = IntegerType()
elif types.is_int64(at):
spark_type = LongType()
elif types.is_float32(at):
spark_type = FloatType()
elif types.is_float64(at):
spark_type = DoubleType()
elif types.is_decimal(at):
spark_type = DecimalType(precision=at.precision, scale=at.scale)
elif types.is_string(at):
spark_type = StringType()
elif types.is_large_string(at):
spark_type = StringType()
elif types.is_binary(at):
spark_type = BinaryType()
elif types.is_fixed_size_binary(at):
spark_type = BinaryType()
elif types.is_large_binary(at):
spark_type = BinaryType()
elif types.is_date32(at):
spark_type = DateType()
elif types.is_timestamp(at) and prefer_timestamp_ntz and at.tz is None:
spark_type = TimestampNTZType()
elif types.is_timestamp(at):
spark_type = TimestampType()
elif types.is_duration(at):
spark_type = DayTimeIntervalType()
elif types.is_list(at):
spark_type = ArrayType(from_arrow_type(at.value_type, prefer_timestamp_ntz))
elif types.is_fixed_size_list(at):
import pyarrow as pa
if LooseVersion(pa.__version__) < LooseVersion("14.0.0"):
# PyArrow versions before 14.0.0 do not support casting FixedSizeListArray to ListArray
raise PySparkTypeError(
error_class="UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION",
message_parameters={"data_type": str(at)},
)
spark_type = ArrayType(from_arrow_type(at.value_type, prefer_timestamp_ntz))
elif types.is_large_list(at):
spark_type = ArrayType(from_arrow_type(at.value_type, prefer_timestamp_ntz))
elif types.is_map(at):
spark_type = MapType(
from_arrow_type(at.key_type, prefer_timestamp_ntz),
from_arrow_type(at.item_type, prefer_timestamp_ntz),
)
elif types.is_struct(at):
return StructType(
[
StructField(
field.name,
from_arrow_type(field.type, prefer_timestamp_ntz),
nullable=field.nullable,
)
for field in at
]
)
elif types.is_dictionary(at):
spark_type = from_arrow_type(at.value_type, prefer_timestamp_ntz)
elif types.is_null(at):
spark_type = NullType()
else:
raise PySparkTypeError(
error_class="UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION",
message_parameters={"data_type": str(at)},
)
return spark_type
def from_arrow_schema(arrow_schema: "pa.Schema", prefer_timestamp_ntz: bool = False) -> StructType:
"""Convert schema from Arrow to Spark."""
return StructType(
[
StructField(
field.name,
from_arrow_type(field.type, prefer_timestamp_ntz),
nullable=field.nullable,
)
for field in arrow_schema
]
)
def _get_local_timezone() -> str:
"""Get local timezone using pytz with environment variable, or dateutil.
If there is a 'TZ' environment variable, pass it to pandas to use pytz and use it as timezone
string, otherwise use the special word 'dateutil/:' which means that pandas uses dateutil and
it reads system configuration to know the system local timezone.
See also:
- https://github.com/pandas-dev/pandas/blob/0.19.x/pandas/tslib.pyx#L1753
- https://github.com/dateutil/dateutil/blob/2.6.1/dateutil/tz/tz.py#L1338
"""
import os
return os.environ.get("TZ", "dateutil/:")
def _check_arrow_array_timestamps_localize(
a: Union["pa.Array", "pa.ChunkedArray"],
dt: DataType,
truncate: bool = True,
timezone: Optional[str] = None,
) -> Union["pa.Array", "pa.ChunkedArray"]:
"""
Convert Arrow timestamps to timezone-naive in the specified timezone if the specified Spark
data type is TimestampType, and optionally truncate nanosecond timestamps to microseconds.
This function works on Arrow Arrays and ChunkedArrays, and it recurses to convert nested
timestamps.
Parameters
----------
a : :class:`pyarrow.Array` or :class:`pyarrow.ChunkedArray`
dt : :class:`DataType`
The Spark data type corresponding to the Arrow Array to be converted.
truncate : bool, default True
Whether to truncate nanosecond timestamps to microseconds. (default ``True``)
timezone : str, optional
The timezone to convert from. If there is a timestamp type, it's required.
Returns
-------
:class:`pyarrow.Array` or :class:`pyarrow.ChunkedArray`
"""
import pyarrow.types as types
import pyarrow as pa
import pyarrow.compute as pc
if isinstance(a, pa.ChunkedArray) and (types.is_nested(a.type) or types.is_dictionary(a.type)):
return pa.chunked_array(
[
_check_arrow_array_timestamps_localize(chunk, dt, truncate, timezone)
for chunk in a.iterchunks()
]
)
if types.is_timestamp(a.type) and truncate and a.type.unit == "ns":
a = pc.floor_temporal(a, unit="microsecond")
if types.is_timestamp(a.type) and a.type.tz is None and type(dt) == TimestampType:
assert timezone is not None
# Only localize timestamps that will become Spark TimestampType columns.
# Do not localize timestamps that will become Spark TimestampNTZType columns.
return pc.assume_timezone(a, timezone)
if types.is_list(a.type):
# Return the ListArray as-is if it contains no nested fields or timestamps
if not types.is_nested(a.type.value_type) and not types.is_timestamp(a.type.value_type):
return a
at: ArrayType = cast(ArrayType, dt)
return pa.ListArray.from_arrays(
a.offsets,
_check_arrow_array_timestamps_localize(a.values, at.elementType, truncate, timezone),
mask=a.is_null() if a.null_count else None,
)
if types.is_map(a.type):
# Return the MapArray as-is if it contains no nested fields or timestamps
if (
not types.is_nested(a.type.key_type)
and not types.is_nested(a.type.item_type)
and not types.is_timestamp(a.type.key_type)
and not types.is_timestamp(a.type.item_type)
):
return a
mt: MapType = cast(MapType, dt)
# TODO(SPARK-48302): Do not replace nulls in MapArray with empty lists
return pa.MapArray.from_arrays(
a.offsets,
_check_arrow_array_timestamps_localize(a.keys, mt.keyType, truncate, timezone),
_check_arrow_array_timestamps_localize(a.items, mt.valueType, truncate, timezone),
)
if types.is_struct(a.type):
# Return the StructArray as-is if it contains no nested fields or timestamps
if all(
[
not types.is_nested(a.type.field(i).type)
and not types.is_timestamp(a.type.field(i).type)
for i in range(a.type.num_fields)
]
):
return a
st: StructType = cast(StructType, dt)
assert len(a.type) == len(st.fields)
return pa.StructArray.from_arrays(
[
_check_arrow_array_timestamps_localize(
a.field(i), st.fields[i].dataType, truncate, timezone
)
for i in range(len(a.type))
],
[a.type[i].name for i in range(len(a.type))],
mask=a.is_null() if a.null_count else None,
)
if types.is_dictionary(a.type):
return pa.DictionaryArray.from_arrays(
a.indices,
_check_arrow_array_timestamps_localize(a.dictionary, dt, truncate, timezone),
)
return a
def _check_arrow_table_timestamps_localize(
table: "pa.Table", schema: StructType, truncate: bool = True, timezone: Optional[str] = None
) -> "pa.Table":
"""
Convert timestamps in a PyArrow Table to timezone-naive in the specified timezone if the
corresponding Spark data type is TimestampType in the specified Spark schema is TimestampType,
and optionally truncate nanosecond timestamps to microseconds.
Parameters
----------
table : :class:`pyarrow.Table`
schema : :class:`StructType`
The Spark schema corresponding to the schema of the Arrow Table.
truncate : bool, default True
Whether to truncate nanosecond timestamps to microseconds. (default ``True``)
timezone : str, optional
The timezone to convert from. If there is a timestamp type, it's required.
Returns
-------
:class:`pyarrow.Table`
"""
import pyarrow.types as types
import pyarrow as pa
# Return the table as-is if it contains no nested fields or timestamps
if all([not types.is_nested(at) and not types.is_timestamp(at) for at in table.schema.types]):
return table
assert len(table.schema) == len(schema.fields)
return pa.Table.from_arrays(
[
_check_arrow_array_timestamps_localize(a, f.dataType, truncate, timezone)
for a, f in zip(table.columns, schema.fields)
],
schema=table.schema,
)
def _check_series_localize_timestamps(s: "PandasSeriesLike", timezone: str) -> "PandasSeriesLike":
"""
Convert timezone aware timestamps to timezone-naive in the specified timezone or local timezone.
If the input series is not a timestamp series, then the same series is returned. If the input
series is a timestamp series, then a converted series is returned.
Parameters
----------
s : pandas.Series
timezone : str
the timezone to convert. if None then use local timezone
Returns
-------
pandas.Series
`pandas.Series` that have been converted to tz-naive
"""
from pyspark.sql.pandas.utils import require_minimum_pandas_version
require_minimum_pandas_version()
import pandas as pd
tz = timezone or _get_local_timezone()
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if isinstance(s.dtype, pd.DatetimeTZDtype):
return s.dt.tz_convert(tz).dt.tz_localize(None)
else:
return s
def _check_series_convert_timestamps_internal(
s: "PandasSeriesLike", timezone: str
) -> "PandasSeriesLike":
"""
Convert a tz-naive timestamp in the specified timezone or local timezone to UTC normalized for
Spark internal storage
Parameters
----------
s : pandas.Series
timezone : str
the timezone to convert. if None then use local timezone
Returns
-------
pandas.Series
`pandas.Series` where if it is a timestamp, has been UTC normalized without a time zone
"""
from pyspark.sql.pandas.utils import require_minimum_pandas_version
require_minimum_pandas_version()
import pandas as pd
from pandas.api.types import ( # type: ignore[attr-defined]
is_datetime64_dtype,
)
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if is_datetime64_dtype(s.dtype):
# When tz_localize a tz-naive timestamp, the result is ambiguous if the tz-naive
# timestamp is during the hour when the clock is adjusted backward during due to
# daylight saving time (dst).
# E.g., for America/New_York, the clock is adjusted backward on 2015-11-01 2:00 to
# 2015-11-01 1:00 from dst-time to standard time, and therefore, when tz_localize
# a tz-naive timestamp 2015-11-01 1:30 with America/New_York timezone, it can be either
# dst time (2015-01-01 1:30-0400) or standard time (2015-11-01 1:30-0500).
#
# Here we explicit choose to use standard time. This matches the default behavior of
# pytz.
#
# Here are some code to help understand this behavior:
# >>> import datetime
# >>> import pandas as pd
# >>> import pytz
# >>>
# >>> t = datetime.datetime(2015, 11, 1, 1, 30)
# >>> ts = pd.Series([t])
# >>> tz = pytz.timezone('America/New_York')
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=True)
# 0 2015-11-01 01:30:00-04:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> ts.dt.tz_localize(tz, ambiguous=False)
# 0 2015-11-01 01:30:00-05:00
# dtype: datetime64[ns, America/New_York]
# >>>
# >>> str(tz.localize(t))
# '2015-11-01 01:30:00-05:00'
tz = timezone or _get_local_timezone()
return s.dt.tz_localize(tz, ambiguous=False).dt.tz_convert("UTC")
elif isinstance(s.dtype, pd.DatetimeTZDtype):
return s.dt.tz_convert("UTC")
else:
return s
def _check_series_convert_timestamps_localize(
s: "PandasSeriesLike", from_timezone: Optional[str], to_timezone: Optional[str]
) -> "PandasSeriesLike":
"""
Convert timestamp to timezone-naive in the specified timezone or local timezone
Parameters
----------
s : pandas.Series
from_timezone : str
the timezone to convert from. if None then use local timezone
to_timezone : str
the timezone to convert to. if None then use local timezone
Returns
-------
pandas.Series
`pandas.Series` where if it is a timestamp, has been converted to tz-naive
"""
from pyspark.sql.pandas.utils import require_minimum_pandas_version
require_minimum_pandas_version()
import pandas as pd
from pandas.api.types import ( # type: ignore[attr-defined]
is_datetime64_dtype,
)
from_tz = from_timezone or _get_local_timezone()
to_tz = to_timezone or _get_local_timezone()
# TODO: handle nested timestamps, such as ArrayType(TimestampType())?
if isinstance(s.dtype, pd.DatetimeTZDtype):
return s.dt.tz_convert(to_tz).dt.tz_localize(None)
elif is_datetime64_dtype(s.dtype) and from_tz != to_tz:
# `s.dt.tz_localize('tzlocal()')` doesn't work properly when including NaT.
return cast(
"PandasSeriesLike",
s.apply(
lambda ts: ts.tz_localize(from_tz, ambiguous=False)
.tz_convert(to_tz)
.tz_localize(None)
if ts is not pd.NaT
else pd.NaT
),
)
else:
return s
def _check_series_convert_timestamps_local_tz(
s: "PandasSeriesLike", timezone: str
) -> "PandasSeriesLike":
"""
Convert timestamp to timezone-naive in the specified timezone or local timezone
Parameters
----------
s : pandas.Series
timezone : str
the timezone to convert to. if None then use local timezone
Returns
-------
pandas.Series
`pandas.Series` where if it is a timestamp, has been converted to tz-naive
"""
return _check_series_convert_timestamps_localize(s, None, timezone)
def _check_series_convert_timestamps_tz_local(
s: "PandasSeriesLike", timezone: str
) -> "PandasSeriesLike":
"""
Convert timestamp to timezone-naive in the specified timezone or local timezone
Parameters
----------
s : pandas.Series
timezone : str
the timezone to convert from. if None then use local timezone
Returns
-------
pandas.Series
`pandas.Series` where if it is a timestamp, has been converted to tz-naive
"""
return _check_series_convert_timestamps_localize(s, timezone, None)
def _convert_map_items_to_dict(s: "PandasSeriesLike") -> "PandasSeriesLike":
"""
Convert a series with items as list of (key, value), as made from an Arrow column of map type,
to dict for compatibility with non-arrow MapType columns.
:param s: pandas.Series of lists of (key, value) pairs
:return: pandas.Series of dictionaries
"""
return cast("PandasSeriesLike", s.apply(lambda m: None if m is None else {k: v for k, v in m}))
def _convert_dict_to_map_items(s: "PandasSeriesLike") -> "PandasSeriesLike":
"""
Convert a series of dictionaries to list of (key, value) pairs to match expected data
for Arrow column of map type.
:param s: pandas.Series of dictionaries
:return: pandas.Series of lists of (key, value) pairs
"""
return cast("PandasSeriesLike", s.apply(lambda d: list(d.items()) if d is not None else None))
def _to_corrected_pandas_type(dt: DataType) -> Optional[Any]:
"""
When converting Spark SQL records to Pandas `pandas.DataFrame`, the inferred data type
may be wrong. This method gets the corrected data type for Pandas if that type may be
inferred incorrectly.
"""
import numpy as np
if type(dt) == ByteType:
return np.int8
elif type(dt) == ShortType:
return np.int16
elif type(dt) == IntegerType:
return np.int32
elif type(dt) == LongType:
return np.int64
elif type(dt) == FloatType:
return np.float32
elif type(dt) == DoubleType:
return np.float64
elif type(dt) == BooleanType:
return bool
elif type(dt) == TimestampType:
return np.dtype("datetime64[ns]")
elif type(dt) == TimestampNTZType:
return np.dtype("datetime64[ns]")
elif type(dt) == DayTimeIntervalType:
return np.dtype("timedelta64[ns]")
else:
return None
def _create_converter_to_pandas(
data_type: DataType,
nullable: bool = True,
*,
timezone: Optional[str] = None,
struct_in_pandas: Optional[str] = None,
error_on_duplicated_field_names: bool = True,
timestamp_utc_localized: bool = True,
ndarray_as_list: bool = False,
) -> Callable[["pd.Series"], "pd.Series"]:
"""
Create a converter of pandas Series that is created from Spark's Python objects,
or `pyarrow.Table.to_pandas` method.
Parameters
----------
data_type : :class:`DataType`
The data type corresponding to the pandas Series to be converted.
nullable : bool, optional
Whether the column is nullable or not. (default ``True``)
timezone : str, optional
The timezone to convert from. If there is a timestamp type, it's required.
struct_in_pandas : str, optional
How to handle struct type. If there is a struct type, it's required.
When ``row``, :class:`Row` object will be used.
When ``dict``, :class:`dict` will be used. If there are duplicated field names,
The fields will be suffixed, like `a_0`, `a_1`.
Must be one of: ``row``, ``dict``.
error_on_duplicated_field_names : bool, optional
Whether raise an exception when there are duplicated field names.
(default ``True``)
timestamp_utc_localized : bool, optional
Whether the timestamp values are localized to UTC or not.
The timestamp values from Arrow are localized to UTC,
whereas the ones from `df.collect()` are localized to the local timezone.
ndarray_as_list : bool, optional
Whether `np.ndarray` is converted to a list or not (default ``False``).
Returns
-------
The converter of `pandas.Series`
"""
import numpy as np
import pandas as pd
pandas_type = _to_corrected_pandas_type(data_type)
if pandas_type is not None:
# SPARK-21766: if an integer field is nullable and has null values, it can be
# inferred by pandas as a float column. If we convert the column with NaN back
# to integer type e.g., np.int16, we will hit an exception. So we use the
# pandas-inferred float type, rather than the corrected type from the schema
# in this case.
if isinstance(data_type, IntegralType) and nullable:
def correct_dtype(pser: pd.Series) -> pd.Series:
if pser.isnull().any():
return pser.astype(np.float64, copy=False)
else:
return pser.astype(pandas_type, copy=False)
elif isinstance(data_type, BooleanType) and nullable:
def correct_dtype(pser: pd.Series) -> pd.Series:
if pser.isnull().any():
return pser.astype(object, copy=False)
else:
return pser.astype(pandas_type, copy=False)
elif isinstance(data_type, TimestampType):
assert timezone is not None
def correct_dtype(pser: pd.Series) -> pd.Series:
if not isinstance(pser.dtype, pd.DatetimeTZDtype):
pser = pser.astype(pandas_type, copy=False)
return _check_series_convert_timestamps_local_tz(pser, timezone=timezone)
else:
def correct_dtype(pser: pd.Series) -> pd.Series:
return pser.astype(pandas_type, copy=False)
return correct_dtype
def _converter(
dt: DataType, _struct_in_pandas: Optional[str], _ndarray_as_list: bool
) -> Optional[Callable[[Any], Any]]:
if isinstance(dt, ArrayType):
_element_conv = _converter(dt.elementType, _struct_in_pandas, _ndarray_as_list)
if _ndarray_as_list:
if _element_conv is None:
def convert_array_ndarray_as_list(value: Any) -> Any:
# In Arrow Python UDF, ArrayType is converted to `np.ndarray`
# whereas a list is expected.
return list(value)
else:
assert _element_conv is not None
def convert_array_ndarray_as_list(value: Any) -> Any:
# In Arrow Python UDF, ArrayType is converted to `np.ndarray`
# whereas a list is expected.
return [_element_conv(v) if v is not None else None for v in value]
return convert_array_ndarray_as_list
else:
if _element_conv is None:
return None
assert _element_conv is not None
def convert_array_ndarray_as_ndarray(value: Any) -> Any:
if isinstance(value, np.ndarray):
# `pyarrow.Table.to_pandas` uses `np.ndarray`.
return np.array(
[_element_conv(v) if v is not None else None for v in value]
)
else:
# otherwise, `list` should be used.
return [_element_conv(v) if v is not None else None for v in value]
return convert_array_ndarray_as_ndarray
elif isinstance(dt, MapType):
_key_conv = _converter(dt.keyType, _struct_in_pandas, _ndarray_as_list)
_value_conv = _converter(dt.valueType, _struct_in_pandas, _ndarray_as_list)
if _key_conv is None and _value_conv is None:
def convert_map(value: Any) -> Any:
# `pyarrow.Table.to_pandas` uses `list` of key-value tuple.
# otherwise, `dict` should be used.
return dict(value)
else:
def convert_map(value: Any) -> Any:
if isinstance(value, list):
# `pyarrow.Table.to_pandas` uses `list` of key-value tuple.
return {
(_key_conv(k) if _key_conv is not None and k is not None else k): (
_value_conv(v) if _value_conv is not None and v is not None else v
)
for k, v in value
}
else:
# otherwise, `dict` should be used.
return {
(_key_conv(k) if _key_conv is not None and k is not None else k): (
_value_conv(v) if _value_conv is not None and v is not None else v
)
for k, v in value.items()
}
return convert_map
elif isinstance(dt, StructType):
assert _struct_in_pandas is not None
field_names = dt.names
if error_on_duplicated_field_names and len(set(field_names)) != len(field_names):
raise UnsupportedOperationException(
error_class="DUPLICATED_FIELD_NAME_IN_ARROW_STRUCT",
message_parameters={"field_names": str(field_names)},
)
dedup_field_names = _dedup_names(field_names)
field_convs = [
_converter(f.dataType, _struct_in_pandas, _ndarray_as_list) for f in dt.fields
]
if _struct_in_pandas == "row":
if all(conv is None for conv in field_convs):
def convert_struct_as_row(value: Any) -> Any:
if isinstance(value, dict):
# `pyarrow.Table.to_pandas` uses `dict`.
_values = [
value.get(name, None) for i, name in enumerate(dedup_field_names)
]
return _create_row(field_names, _values)
else:
# otherwise, `Row` should be used.
return _create_row(field_names, value)
else:
def convert_struct_as_row(value: Any) -> Any:
if isinstance(value, dict):
# `pyarrow.Table.to_pandas` uses `dict`.
_values = [
conv(v) if conv is not None and v is not None else v
for conv, v in zip(
field_convs,
(value.get(name, None) for name in dedup_field_names),
)
]
return _create_row(field_names, _values)
else:
# otherwise, `Row` should be used.
_values = [
conv(v) if conv is not None and v is not None else v
for conv, v in zip(field_convs, value)
]
return _create_row(field_names, _values)
return convert_struct_as_row
elif _struct_in_pandas == "dict":
if all(conv is None for conv in field_convs):
def convert_struct_as_dict(value: Any) -> Any:
if isinstance(value, dict):
# `pyarrow.Table.to_pandas` uses `dict`.
return {name: value.get(name, None) for name in dedup_field_names}
else:
# otherwise, `Row` should be used.
return dict(zip(dedup_field_names, value))
else:
def convert_struct_as_dict(value: Any) -> Any:
if isinstance(value, dict):
# `pyarrow.Table.to_pandas` uses `dict`.
return {
name: conv(v) if conv is not None and v is not None else v
for name, conv, v in zip(
dedup_field_names,
field_convs,
(value.get(name, None) for name in dedup_field_names),
)
}
else:
# otherwise, `Row` should be used.
return {
name: conv(v) if conv is not None and v is not None else v
for name, conv, v in zip(dedup_field_names, field_convs, value)
}
return convert_struct_as_dict
else:
raise PySparkValueError(
error_class="UNKNOWN_VALUE_FOR",
message_parameters={"var": str(_struct_in_pandas)},
)
elif isinstance(dt, TimestampType):
assert timezone is not None
local_tz: Union[datetime.tzinfo, str] = (
datetime.timezone.utc if timestamp_utc_localized else _get_local_timezone()
)
def convert_timestamp(value: Any) -> Any:
if isinstance(value, datetime.datetime) and value.tzinfo is not None:
ts = pd.Timestamp(value)
else:
ts = pd.Timestamp(value).tz_localize(local_tz)
return ts.tz_convert(timezone).tz_localize(None)
return convert_timestamp
elif isinstance(dt, TimestampNTZType):
def convert_timestamp_ntz(value: Any) -> Any:
return pd.Timestamp(value)
return convert_timestamp_ntz
elif isinstance(dt, UserDefinedType):
udt: UserDefinedType = dt
conv = _converter(udt.sqlType(), _struct_in_pandas="row", _ndarray_as_list=True)
if conv is None:
def convert_udt(value: Any) -> Any:
if hasattr(value, "__UDT__"):