|
| 1 | +# Copyright (c) 2025, Salesforce, Inc. |
| 2 | +# SPDX-License-Identifier: Apache-2 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING |
| 18 | + |
| 19 | +import pandas.api.types as pd_types |
| 20 | +from pyspark.sql.types import ( |
| 21 | + BooleanType, |
| 22 | + DoubleType, |
| 23 | + LongType, |
| 24 | + StringType, |
| 25 | + StructField, |
| 26 | + StructType, |
| 27 | + TimestampType, |
| 28 | +) |
| 29 | + |
| 30 | +if TYPE_CHECKING: |
| 31 | + import pandas |
| 32 | + from pyspark.sql.types import AtomicType |
| 33 | + |
| 34 | +PANDAS_TYPE_MAPPING = { |
| 35 | + "object": StringType(), |
| 36 | + "int64": LongType(), |
| 37 | + "float64": DoubleType(), |
| 38 | + "bool": BooleanType(), |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +def _pandas_to_spark_schema( |
| 43 | + pandas_df: pandas.DataFrame, nullable: bool = True |
| 44 | +) -> StructType: |
| 45 | + fields = [] |
| 46 | + for column, dtype in pandas_df.dtypes.items(): |
| 47 | + spark_type: AtomicType |
| 48 | + if pd_types.is_datetime64_any_dtype(dtype): |
| 49 | + spark_type = TimestampType() |
| 50 | + else: |
| 51 | + spark_type = PANDAS_TYPE_MAPPING.get(str(dtype), StringType()) |
| 52 | + fields.append(StructField(column, spark_type, nullable)) |
| 53 | + return StructType(fields) |
0 commit comments