itholic opened a new pull request, #45699:
URL: https://github.com/apache/spark/pull/45699

   ### What changes were proposed in this pull request?
   
   This PR proposes to inferring `dict` as `MapType` from Pandas DataFrame to 
allow DataFrame creation.
   
   This PR also introduces new config `INFER_PANDAS_DICT_AS_MAP` to reach the 
goal.
   
   ### Why are the changes needed?
   
   Currently the PyArrow infers the Pandas dictionary field as `StructType` 
instead of `MapType`:
   
   ```python
   >>> pdf = pd.DataFrame({"str_col": ['second'], "dict_col": [{'first': 0.7, 
'second': 0.3}]})
   >>> pa.Schema.from_pandas(pdf)
   str_col: string
   dict_col: struct<first: double, second: double>
     child 0, first: double
     child 1, second: double
   ```
   
   The problem is that this behavior make Spark cannot handle the schema 
properly:
   
   ```python
   >>> sdf = spark.createDataFrame(pdf)
   >>> sdf.withColumn("test", F.col("dict_col")[F.col("str_col")]).show()
   [INVALID_EXTRACT_FIELD_TYPE] Field name should be a non-null string literal, 
but it's "str_col". SQLSTATE: 42000
   ```
   
   
   ### Does this PR introduce _any_ user-facing change?
   
   No default behavior changes, but `createDataFrame` inferring `dict` as a 
`MapType` from Pandas DataFrame when `INFER_PANDAS_DICT_AS_MAP` set to `True`:
   
   **Before**
   ```python
   >>> pdf = pd.DataFrame({"str_col": ['second'], "dict_col": [{'first': 0.7, 
'second': 0.3}]})
   >>> sdf = spark.createDataFrame(pdf)
   >>> sdf.withColumn("test", F.col("dict_col")[F.col("str_col")]).show()
   [INVALID_EXTRACT_FIELD_TYPE] Field name should be a non-null string literal, 
but it's "str_col". SQLSTATE: 42000
   ```
   
   **After**
   ```python
   >>> spark.conf.set("spark.sql.execution.pandas.inferPandasDictAsMap", True)
   >>> pdf = pd.DataFrame({"str_col": ['second'], "dict_col": [{'first': 0.7, 
'second': 0.3}]})
   >>> sdf = spark.createDataFrame(pdf)
   >>> sdf.withColumn("test", 
F.col("dict_col")[F.col("str_col")]).show(truncate=False)
   +-------+-----------------------------+----+
   |str_col|dict_col                     |test|
   +-------+-----------------------------+----+
   |second |{first -> 0.7, second -> 0.3}|0.3 |
   +-------+-----------------------------+----+
   ```
   
   
   ### How was this patch tested?
   
   Added UT.
   
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   No.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to