There is a pyspark dataframe with missing values:
tbl = sc.parallelize([
Row(first_name='Alice', last_name='Cooper'),
Row(first_name='Prince', last_name=None),
Row(first_name=None, last_name='Lenon')
]).toDF()
tbl.show()
Here's the table:
+----------+---------+
|first_name|last_name|
+----------+---------+
| Alice| Cooper|
| Prince| null|
| null| Lenon|
+----------+---------+
I would like to create a new column as follows:
I can construct a simple function:
def combine_data(row):
if row.last_name is None:
return row.first_name
elif row.first_name is None:
return row.last_name
else:
return '%s %s' % (row.first_name, row.last_name)
tbl.map(combine_data).collect()
I do get the correct result, but I can't append it to the table as a column: tbl.withColumn('new_col', tbl.map(combine_data))
results in AssertionError: col should be Column
What is the best way to convert the result of map
to a Column
? Is there a preferred way to deal with null
values?
As always it is best to operate directly on native representation instead of fetching data to Python:
from pyspark.sql.functions import concat_ws, coalesce, lit, trim
def combine(*cols):
return trim(concat_ws(" ", *[coalesce(c, lit("")) for c in cols]))
tbl.withColumn("foo", combine("first_name", "last_name")).
You just need to use a UDF that receives two columns
as arguments.
from pyspark.sql.functions import *
from pyspark.sql import Row
tbl = sc.parallelize([
Row(first_name='Alice', last_name='Cooper'),
Row(first_name='Prince', last_name=None),
Row(first_name=None, last_name='Lenon')
]).toDF()
tbl.show()
def combine(c1, c2):
if c1 != None and c2 != None:
return c1 + " " + c2
elif c1 == None:
return c2
else:
return c1
combineUDF = udf(combine)
expr = [c for c in ["first_name", "last_name"]] + [combineUDF(col("first_name"), col("last_name")).alias("full_name")]
tbl.select(*expr).show()
#+----------+---------+------------+
#|first_name|last_name| full_name|
#+----------+---------+------------+
#| Alice| Cooper|Alice Cooper|
#| Prince| null| Prince|
#| null| Lenon| Lenon|
#+----------+---------+------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With