You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ru...@apache.org on 2026/03/30 11:32:12 UTC

(spark) branch master updated: [SPARK-56256][PYTHON] Add emptyDataFrame API to SparkSession

This is an automated email from the ASF dual-hosted git repository.

ruifengz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 1f9a0c76386f [SPARK-56256][PYTHON] Add emptyDataFrame API to SparkSession
1f9a0c76386f is described below

commit 1f9a0c76386f690cbe87dd19615f8ad1ff4ed6f4
Author: Ruifeng Zheng <ru...@apache.org>
AuthorDate: Mon Mar 30 19:31:57 2026 +0800

    [SPARK-56256][PYTHON] Add emptyDataFrame API to SparkSession
    
    ### What changes were proposed in this pull request?
    
    Add a new `SparkSession.emptyDataFrame(schema)` API that creates an empty DataFrame with the specified schema.
    
    ### Why are the changes needed?
    
    Creating an empty DataFrame with a given schema is a common operation, but currently requires calling `spark.createDataFrame([], schema)` which is not very intuitive. This new API provides a more readable and discoverable way to create empty DataFrames.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Adds a new public API `SparkSession.emptyDataFrame(schema: Union[StructType, str]) -> DataFrame`.
    
    ### How was this patch tested?
    
    Added unit tests in `test_creation.py` covering both `StructType` and DDL string schema inputs. Tests are shared via the mixin and run for both classic and Spark Connect.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Yes. Generated-by Claude Code (Opus 4.6)
    
    Closes #55055 from zhengruifeng/emptyDataFrame.
    
    Authored-by: Ruifeng Zheng <ru...@apache.org>
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
---
 python/pyspark/sql/connect/session.py     |  5 ++++
 python/pyspark/sql/session.py             | 44 +++++++++++++++++++++++++++++++
 python/pyspark/sql/tests/test_creation.py | 23 ++++++++++++++++
 3 files changed, 72 insertions(+)

diff --git a/python/pyspark/sql/connect/session.py b/python/pyspark/sql/connect/session.py
index 8a37c2a25470..3edab12d852b 100644
--- a/python/pyspark/sql/connect/session.py
+++ b/python/pyspark/sql/connect/session.py
@@ -796,6 +796,11 @@ class SparkSession:
 
     createDataFrame.__doc__ = PySparkSession.createDataFrame.__doc__
 
+    def emptyDataFrame(self, schema: Union[StructType, str]) -> "ParentDataFrame":
+        return self.createDataFrame([], schema)
+
+    emptyDataFrame.__doc__ = PySparkSession.emptyDataFrame.__doc__
+
     def sql(
         self,
         sqlQuery: str,
diff --git a/python/pyspark/sql/session.py b/python/pyspark/sql/session.py
index 5ea575eca719..e782f2f79db4 100644
--- a/python/pyspark/sql/session.py
+++ b/python/pyspark/sql/session.py
@@ -1704,6 +1704,50 @@ class SparkSession(SparkConversionMixin):
         df._schema = struct
         return df
 
+    def emptyDataFrame(self, schema: Union[StructType, str]) -> "ParentDataFrame":
+        """Creates an empty :class:`DataFrame` with the specified schema.
+
+        .. versionadded:: 4.2.0
+
+        Parameters
+        ----------
+        schema : :class:`StructType` or str
+            a :class:`StructType` or a DDL-formatted string that describes the schema.
+
+        Returns
+        -------
+        :class:`DataFrame`
+            An empty DataFrame with the specified schema.
+
+        Examples
+        --------
+        Create an empty DataFrame with a StructType schema.
+
+        >>> from pyspark.sql.types import StructType, StructField, StringType, IntegerType
+        >>> schema = StructType([
+        ...     StructField("name", StringType(), True),
+        ...     StructField("age", IntegerType(), True)
+        ... ])
+        >>> df = spark.emptyDataFrame(schema)
+        >>> df.printSchema()
+        root
+         |-- name: string (nullable = true)
+         |-- age: integer (nullable = true)
+        >>> df.count()
+        0
+
+        Create an empty DataFrame with a DDL-formatted string schema.
+
+        >>> df = spark.emptyDataFrame("name STRING, age INT")
+        >>> df.printSchema()
+        root
+         |-- name: string (nullable = true)
+         |-- age: integer (nullable = true)
+        >>> df.count()
+        0
+        """
+        return self.createDataFrame([], schema)
+
     def sql(
         self, sqlQuery: str, args: Optional[Union[Dict[str, Any], List]] = None, **kwargs: Any
     ) -> "ParentDataFrame":
diff --git a/python/pyspark/sql/tests/test_creation.py b/python/pyspark/sql/tests/test_creation.py
index 6c2a454ddaf7..0c77faf9fe3b 100644
--- a/python/pyspark/sql/tests/test_creation.py
+++ b/python/pyspark/sql/tests/test_creation.py
@@ -23,6 +23,7 @@ from pyspark.sql import Row
 import pyspark.sql.functions as F
 from pyspark.sql.types import (
     DecimalType,
+    IntegerType,
     StructType,
     StructField,
     StringType,
@@ -258,6 +259,28 @@ class DataFrameCreationTestsMixin:
                 [Row(str_col="second", dict_col={"first": 0.7, "second": 0.3}, test=0.3)],
             )
 
+    def test_empty_dataframe_with_struct_type(self):
+        schema = StructType(
+            [
+                StructField("name", StringType(), True),
+                StructField("age", IntegerType(), True),
+            ]
+        )
+        df = self.spark.emptyDataFrame(schema)
+        self.assertEqual(df.schema, schema)
+        self.assertEqual(df.count(), 0)
+        self.assertEqual(df.collect(), [])
+
+    def test_empty_dataframe_with_ddl_string(self):
+        df = self.spark.emptyDataFrame("name STRING, age INT")
+        self.assertEqual(len(df.schema.fields), 2)
+        self.assertEqual(df.schema.fields[0].name, "name")
+        self.assertIsInstance(df.schema.fields[0].dataType, StringType)
+        self.assertEqual(df.schema.fields[1].name, "age")
+        self.assertIsInstance(df.schema.fields[1].dataType, IntegerType)
+        self.assertEqual(df.count(), 0)
+        self.assertEqual(df.collect(), [])
+
     def test_empty_schema(self):
         schema = StructType()
         for data in [[], [Row()]]:


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org