Explode in PySpark
explode
and split
are SQL functions. Both operate on SQL Column
. split
takes a Java regular expression as a second argument. If you want to separate data on arbitrary whitespace you'll need something like this:
df = sqlContext.createDataFrame(
[('cat \n\n elephant rat \n rat cat', )], ['word']
)
df.select(explode(split(col("word"), "\s+")).alias("word")).show()
## +--------+
## | word|
## +--------+
## | cat|
## |elephant|
## | rat|
## | rat|
## | cat|
## +--------+
To split on whitespace and also remove blank lines, add the where
clause.
DF = sqlContext.createDataFrame([('cat \n\n elephant rat \n rat cat\nmat\n', )], ['word'])
>>> (DF.select(explode(split(DF.word, "\s")).alias("word"))
.where('word != ""')
.show())
+--------+
| word|
+--------+
| cat|
|elephant|
| rat|
| rat|
| cat|
| mat|
+--------+