pyspark.sql.functions.try_to_binary

pyspark.sql.functions.try_to_binary(col: ColumnOrName, format: Optional[ColumnOrName] = None) → pyspark.sql.column.Column[source]

This is a special version of to_binary that performs the same operation, but returns a NULL value instead of raising an error if the conversion cannot be performed.

New in version 3.5.0.

Parameters
colColumn or str

Input column or strings.

formatColumn or str, optional

format to use to convert binary values.

Examples

>>> df = spark.createDataFrame([("abc",)], ["e"])
>>> df.select(try_to_binary(df.e, lit("utf-8")).alias('r')).collect()
[Row(r=bytearray(b'abc'))]
>>> df = spark.createDataFrame([("414243",)], ["e"])
>>> df.select(try_to_binary(df.e).alias('r')).collect()
[Row(r=bytearray(b'ABC'))]