3

I have a pyspark data frame whih has a column containing strings. I want to split this column into words

Code:

>>> sentenceData = sqlContext.read.load('file://sample1.csv', format='com.databricks.spark.csv', header='true', inferSchema='true')
>>> sentenceData.show(truncate=False)
+---+---------------------------+
|key|desc                       |
+---+---------------------------+
|1  |Virat is good batsman      |
|2  |sachin was good            |
|3  |but modi sucks big big time|
|4  |I love the formulas        |
+---+---------------------------+


Expected Output
---------------

>>> sentenceData.show(truncate=False)
+---+-------------------------------------+
|key|desc                                 |
+---+-------------------------------------+
|1  |[Virat,is,good,batsman]              |
|2  |[sachin,was,good]                    |
|3  |....                                 |
|4  |...                                  |
+---+-------------------------------------+

How can I achieve this?

Hardik Gupta
  • 4,700
  • 9
  • 41
  • 83

1 Answers1

18

Use split function:

from pyspark.sql.functions import split

df.withColumn("desc", split("desc", "\s+"))
Alberto Bonsanto
  • 17,556
  • 10
  • 64
  • 93
user7330462
  • 196
  • 1
  • 2