Upgrading PySpark#
Upgrading from PySpark 3.5 to 4.0#
In Spark 4.0, Python 3.8 support was dropped in PySpark.
In Spark 4.0, the minimum supported version for Pandas has been raised from 1.0.5 to 2.0.0 in PySpark.
In Spark 4.0, the minimum supported version for Numpy has been raised from 1.15 to 1.21 in PySpark.
In Spark 4.0, the minimum supported version for PyArrow has been raised from 4.0.0 to 11.0.0 in PySpark.
In Spark 4.0,
Int64IndexandFloat64Indexhave been removed from pandas API on Spark,Indexshould be used directly.In Spark 4.0,
DataFrame.iteritemshas been removed from pandas API on Spark, useDataFrame.itemsinstead.In Spark 4.0,
Series.iteritemshas been removed from pandas API on Spark, useSeries.itemsinstead.In Spark 4.0,
DataFrame.appendhas been removed from pandas API on Spark, useps.concatinstead.In Spark 4.0,
Series.appendhas been removed from pandas API on Spark, useps.concatinstead.In Spark 4.0,
DataFrame.madhas been removed from pandas API on Spark.In Spark 4.0,
Series.madhas been removed from pandas API on Spark.In Spark 4.0,
na_sentinelparameter fromIndex.factorizeandSeries.factorizehas been removed from pandas API on Spark, useuse_na_sentinelinstead.In Spark 4.0,
inplaceparameter fromCategorical.add_categories,Categorical.remove_categories,Categorical.set_categories,Categorical.rename_categories,Categorical.reorder_categories,Categorical.as_ordered,Categorical.as_unorderedhave been removed from pandas API on Spark.In Spark 4.0,
inplaceparameter fromCategoricalIndex.add_categories,CategoricalIndex.remove_categories,CategoricalIndex.remove_unused_categories,CategoricalIndex.set_categories,CategoricalIndex.rename_categories,CategoricalIndex.reorder_categories,CategoricalIndex.as_ordered,CategoricalIndex.as_unorderedhave been removed from pandas API on Spark.In Spark 4.0,
closedparameter fromps.date_rangehas been removed from pandas API on Spark.In Spark 4.0,
include_startandinclude_endparameters fromDataFrame.between_timehave been removed from pandas API on Spark, useinclusiveinstead.In Spark 4.0,
include_startandinclude_endparameters fromSeries.between_timehave been removed from pandas API on Spark, useinclusiveinstead.In Spark 4.0, the various datetime attributes of
DatetimeIndex(day,month,yearetc.) are nowint32instead ofint64from pandas API on Spark.In Spark 4.0,
sort_columnsparameter fromDataFrame.plotandSeries.plothas been removed from pandas API on Spark.In Spark 4.0, the default value of
regexparameter forSeries.str.replacehas been changed fromTruetoFalsefrom pandas API on Spark. Additionally, a single characterpatwithregex=Trueis now treated as a regular expression instead of a string literal.In Spark 4.0, the resulting name from
value_countsfor all objects sets to'count'(or'proportion'ifnormalize=Truewas passed) from pandas API on Spark, and the index will be named after the original object.In Spark 4.0,
squeezeparameter fromps.read_csvandps.read_excelhas been removed from pandas API on Spark.In Spark 4.0,
null_countsparameter fromDataFrame.infohas been removed from pandas API on Spark, useshow_countsinstead.In Spark 4.0, the result of
MultiIndex.appenddoes not keep the index names from pandas API on Spark.In Spark 4.0,
DataFrameGroupBy.aggwith lists respectingas_index=Falsefrom pandas API on Spark.In Spark 4.0,
DataFrame.stackguarantees the order of existing columns instead of sorting them lexicographically from pandas API on Spark.In Spark 4.0,
TrueorFalsetoinclusiveparameter fromSeries.betweenhas been removed from pandas API on Spark, usebothorneitherinstead respectively.In Spark 4.0,
Index.asi8has been removed from pandas API on Spark, useIndex.astypeinstead.In Spark 4.0,
Index.is_type_compatiblehas been removed from pandas API on Spark, useIndex.isininstead.In Spark 4.0,
col_spaceparameter fromDataFrame.to_latexandSeries.to_latexhas been removed from pandas API on Spark.In Spark 4.0,
DataFrame.to_spark_iohas been removed from pandas API on Spark, useDataFrame.spark.to_spark_ioinstead.In Spark 4.0,
Series.is_monotonicandIndex.is_monotonichave been removed from pandas API on Spark, useSeries.is_monotonic_increasingorIndex.is_monotonic_increasinginstead respectively.In Spark 4.0,
DataFrame.get_dtype_countshas been removed from pandas API on Spark, useDataFrame.dtypes.value_counts()instead.In Spark 4.0,
encodingparameter fromDataFrame.to_excelandSeries.to_excelhave been removed from pandas API on Spark.In Spark 4.0,
verboseparameter fromDataFrame.to_excelandSeries.to_excelhave been removed from pandas API on Spark.In Spark 4.0,
mangle_dupe_colsparameter fromread_csvhas been removed from pandas API on Spark.In Spark 4.0,
DataFrameGroupBy.backfillhas been removed from pandas API on Spark, useDataFrameGroupBy.bfillinstead.In Spark 4.0,
DataFrameGroupBy.padhas been removed from pandas API on Spark, useDataFrameGroupBy.ffillinstead.In Spark 4.0,
Index.is_all_dateshas been removed from pandas API on Spark.In Spark 4.0,
convert_floatparameter fromread_excelhas been removed from pandas API on Spark.In Spark 4.0,
mangle_dupe_colsparameter fromread_excelhas been removed from pandas API on Spark.In Spark 4.0,
DataFrame.koalashas been removed from pandas API on Spark, useDataFrame.pandas_on_sparkinstead.In Spark 4.0,
DataFrame.to_koalashas been removed from PySpark, useDataFrame.pandas_apiinstead.In Spark 4.0,
DataFrame.to_pandas_on_sparkhas been removed from PySpark, useDataFrame.pandas_apiinstead.In Spark 4.0,
DatatimeIndex.weekandDatatimeIndex.weekofyearhave been removed from Pandas API on Spark, useDatetimeIndex.isocalendar().weekinstead.In Spark 4.0,
Series.dt.weekandSeries.dt.weekofyearhave been removed from Pandas API on Spark, useSeries.dt.isocalendar().weekinstead.In Spark 4.0, when applying
astypeto a decimal type object, the existing missing value is changed toTrueinstead ofFalsefrom Pandas API on Spark.In Spark 4.0,
pyspark.testing.assertPandasOnSparkEqualhas been removed from Pandas API on Spark, usepyspark.pandas.testing.assert_frame_equalinstead.In Spark 4.0, the aliases
Y,M,H,T,Shave been deprecated from Pandas API on Spark, useYE,ME,h,min,sinstead respectively.In Spark 4.0, the schema of a map column is inferred by merging the schemas of all pairs in the map. To restore the previous behavior where the schema is only inferred from the first non-null pair, you can set
spark.sql.pyspark.legacy.inferMapTypeFromFirstPair.enabledtotrue.In Spark 4.0,
compute.ops_on_diff_framesis on by default. To restore the previous behavior, setcompute.ops_on_diff_framestofalse.In Spark 4.0, the data type
YearMonthIntervalTypeinDataFrame.collectno longer returns the underlying integers. To restore the previous behavior, setPYSPARK_YM_INTERVAL_LEGACYenvironment variable to1.In Spark 4.0, items other than functions (e.g.
DataFrame,Column,StructType) have been removed from the wildcard importfrom pyspark.sql.functions import *, you should import these items from proper modules (e.g.from pyspark.sql import DataFrame, Column,from pyspark.sql.types import StructType).In Spark 4.0, pandas API on Spark will raise an exception if the underlying Spark is working with ANSI mode enabled that is enabled by default, as it will not work properly with ANSI mode. To make it work, you need to explicitly disable ANSI mode by setting
spark.sql.ansi.enabledtofalse. Alternatively you can set a pandas-on-spark optioncompute.fail_on_ansi_modetoFalseto force it to work, although it can cause unexpected behavior.
Upgrading from PySpark 3.3 to 3.4#
In Spark 3.4, the schema of an array column is inferred by merging the schemas of all elements in the array. To restore the previous behavior where the schema is only inferred from the first element, you can set
spark.sql.pyspark.legacy.inferArrayTypeFromFirstElement.enabledtotrue.In Spark 3.4, if Pandas on Spark API
Groupby.apply’sfuncparameter return type is not specified andcompute.shortcut_limitis set to 0, the sampling rows will be set to 2 (ensure sampling rows always >= 2) to make sure infer schema is accurate.In Spark 3.4, if Pandas on Spark API
Index.insertis out of bounds, will raise IndexError withindex {} is out of bounds for axis 0 with size {}to follow pandas 1.4 behavior.In Spark 3.4, the series name will be preserved in Pandas on Spark API
Series.modeto follow pandas 1.4 behavior.In Spark 3.4, the Pandas on Spark API
Index.__setitem__will first to checkvaluetype isColumntype to avoid raising unexpectedValueErrorinis_list_likelike Cannot convert column into bool: please use ‘&’ for ‘and’, ‘|’ for ‘or’, ‘~’ for ‘not’ when building DataFrame boolean expressions..In Spark 3.4, the Pandas on Spark API
astype('category')will also refreshcategories.dtypeaccording to original datadtypeto follow pandas 1.4 behavior.In Spark 3.4, the Pandas on Spark API supports groupby positional indexing in
GroupBy.headandGroupBy.tailto follow pandas 1.4. Negative arguments now work correctly and result in ranges relative to the end and start of each group, Previously, negative arguments returned empty frames.In Spark 3.4, the infer schema process of
groupby.applyin Pandas on Spark, will first infer the pandas type to ensure the accuracy of the pandasdtypeas much as possible.In Spark 3.4, the
Series.concatsort parameter will be respected to follow pandas 1.4 behaviors.In Spark 3.4, the
DataFrame.__setitem__will make a copy and replace pre-existing arrays, which will NOT be over-written to follow pandas 1.4 behaviors.In Spark 3.4, the
SparkSession.sqland the Pandas on Spark APIsqlhave got new parameterargswhich provides binding of named parameters to their SQL literals.In Spark 3.4, Pandas API on Spark follows for the pandas 2.0, and some APIs were deprecated or removed in Spark 3.4 according to the changes made in pandas 2.0. Please refer to the [release notes of pandas](https://pandas.pydata.org/docs/dev/whatsnew/) for more details.
In Spark 3.4, the custom monkey-patch of
collections.namedtuplewas removed, andcloudpicklewas used by default. To restore the previous behavior for any relevant pickling issue ofcollections.namedtuple, setPYSPARK_ENABLE_NAMEDTUPLE_PATCHenvironment variable to1.
Upgrading from PySpark 3.2 to 3.3#
In Spark 3.3, the
pyspark.pandas.sqlmethod follows [the standard Python string formatter](https://docs.python.org/3/library/string.html#format-string-syntax). To restore the previous behavior, setPYSPARK_PANDAS_SQL_LEGACYenvironment variable to1.In Spark 3.3, the
dropmethod of pandas API on Spark DataFrame supports dropping rows byindex, and sets dropping by index instead of column by default.In Spark 3.3, PySpark upgrades Pandas version, the new minimum required version changes from 0.23.2 to 1.0.5.
In Spark 3.3, the
reprreturn values of SQL DataTypes have been changed to yield an object with the same value when passed toeval.
Upgrading from PySpark 3.1 to 3.2#
In Spark 3.2, the PySpark methods from sql, ml, spark_on_pandas modules raise the
TypeErrorinstead ofValueErrorwhen are applied to a param of inappropriate type.In Spark 3.2, the traceback from Python UDFs, pandas UDFs and pandas function APIs are simplified by default without the traceback from the internal Python workers. In Spark 3.1 or earlier, the traceback from Python workers was printed out. To restore the behavior before Spark 3.2, you can set
spark.sql.execution.pyspark.udf.simplifiedTraceback.enabledtofalse.In Spark 3.2, pinned thread mode is enabled by default to map each Python thread to the corresponding JVM thread. Previously, one JVM thread could be reused for multiple Python threads, which resulted in one JVM thread local being shared to multiple Python threads. Also, note that now
pyspark.InheritableThreadorpyspark.inheritable_thread_targetis recommended to use together for a Python thread to properly inherit the inheritable attributes such as local properties in a JVM thread, and to avoid a potential resource leak issue. To restore the behavior before Spark 3.2, you can setPYSPARK_PIN_THREADenvironment variable tofalse.
Upgrading from PySpark 2.4 to 3.0#
In Spark 3.0, PySpark requires a pandas version of 0.23.2 or higher to use pandas related functionality, such as
toPandas,createDataFramefrom pandas DataFrame, and so on.In Spark 3.0, PySpark requires a PyArrow version of 0.12.1 or higher to use PyArrow related functionality, such as
pandas_udf,toPandasandcreateDataFramewith “spark.sql.execution.arrow.enabled=true”, etc.In PySpark, when creating a
SparkSessionwithSparkSession.builder.getOrCreate(), if there is an existingSparkContext, the builder was trying to update theSparkConfof the existingSparkContextwith configurations specified to the builder, but theSparkContextis shared by allSparkSessions, so we should not update them. In 3.0, the builder comes to not update the configurations. This is the same behavior as Java/Scala API in 2.3 and above. If you want to update them, you need to update them prior to creating aSparkSession.In PySpark, when Arrow optimization is enabled, if Arrow version is higher than 0.11.0, Arrow can perform safe type conversion when converting pandas.Series to an Arrow array during serialization. Arrow raises errors when detecting unsafe type conversions like overflow. You enable it by setting
spark.sql.execution.pandas.convertToArrowArraySafelyto true. The default setting is false. PySpark behavior for Arrow versions is illustrated in the following table:PyArrow version
Integer overflow
Floating point truncation
0.11.0 and below
Raise error
Silently allows
> 0.11.0, arrowSafeTypeConversion=false
Silent overflow
Silently allows
> 0.11.0, arrowSafeTypeConversion=true
Raise error
Raise error
In Spark 3.0,
createDataFrame(..., verifySchema=True)validates LongType as well in PySpark. Previously, LongType was not verified and resulted in None in case the value overflows. To restore this behavior, verifySchema can be set to False to disable the validation.As of Spark 3.0,
Rowfield names are no longer sorted alphabetically when constructing with named arguments for Python versions 3.6 and above, and the order of fields will match that as entered. To enable sorted fields by default, as in Spark 2.4, set the environment variablePYSPARK_ROW_FIELD_SORTING_ENABLEDto true for both executors and driver - this environment variable must be consistent on all executors and driver; otherwise, it may cause failures or incorrect answers. For Python versions less than 3.6, the field names will be sorted alphabetically as the only option.In Spark 3.0,
pyspark.ml.param.shared.Has*mixins do not provide anyset*(self, value)setter methods anymore, use the respectiveself.set(self.*, value)instead. See SPARK-29093 for details.
Upgrading from PySpark 2.3 to 2.4#
In PySpark, when Arrow optimization is enabled, previously
toPandasjust failed when Arrow optimization is unable to be used whereascreateDataFramefrom Pandas DataFrame allowed the fallback to non-optimization. Now, bothtoPandasandcreateDataFramefrom Pandas DataFrame allow the fallback by default, which can be switched off byspark.sql.execution.arrow.fallback.enabled.
Upgrading from PySpark 2.3.0 to 2.3.1 and above#
As of version 2.3.1 Arrow functionality, including
pandas_udfandtoPandas()/createDataFrame()withspark.sql.execution.arrow.enabledset toTrue, has been marked as experimental. These are still evolving and not currently recommended for use in production.
Upgrading from PySpark 2.2 to 2.3#
In PySpark, now we need Pandas 0.19.2 or upper if you want to use Pandas related functionalities, such as
toPandas,createDataFramefrom Pandas DataFrame, etc.In PySpark, the behavior of timestamp values for Pandas related functionalities was changed to respect session timezone. If you want to use the old behavior, you need to set a configuration
spark.sql.execution.pandas.respectSessionTimeZoneto False. See SPARK-22395 for details.In PySpark,
na.fill()orfillnaalso accepts boolean and replaces nulls with booleans. In prior Spark versions, PySpark just ignores it and returns the original Dataset/DataFrame.In PySpark,
df.replacedoes not allow to omit value whento_replaceis not a dictionary. Previously, value could be omitted in the other cases and had None by default, which is counterintuitive and error-prone.
Upgrading from PySpark 1.4 to 1.5#
Resolution of strings to columns in Python now supports using dots (.) to qualify the column or access nested values. For example
df['table.column.nestedField']. However, this means that if your column name contains any dots you must now escape them using backticks (e.g.,table.`column.with.dots`.nested).DataFrame.withColumn method in PySpark supports adding a new column or replacing existing columns of the same name.
Upgrading from PySpark 1.0-1.2 to 1.3#
When using DataTypes in Python you will need to construct them (i.e.
StringType()) instead of referencing a singleton.