2017-05-14 4 views
7

मैं एक dataframe है जिसमें निम्न शामिल है:स्तंभ को एकाधिक पंक्तियों में विभाजित करने के लिए (पाइप के साथ विभाजक के रूप में) कैसे?

movieId/movieName/genre 
1   example1 action|thriller|romance 
2   example2 fantastic|action 

मैं (पहले एक से) एक दूसरे dataframe प्राप्त करने के लिए चाहते हैं, जो निम्न शामिल हैं:

movieId/movieName/genre 
1   example1 action 
1   example1 thriller 
1   example1 romance 
2   example2 fantastic 
2   example2 action 

मैं कैसे कर सकते हैं कि ?

उत्तर

9

क्यों अन्य उत्तर split के बाद से UDFs का सुझाव है विस्फोट है स्पार्क एसक्यूएल में मूल कार्य है ?! functions ऑब्जेक्ट देखें।

अन्य दो जवाब को देखते हुए, मुझे लगता है सबसे आसान जवाब इस प्रकार है:

scala> movies.show(truncate = false) 
+-------+---------+-----------------------+ 
|movieId|movieName|genre     | 
+-------+---------+-----------------------+ 
|1  |example1 |action|thriller|romance| 
|2  |example2 |fantastic|action  | 
+-------+---------+-----------------------+ 

scala> movies.withColumn("genre", explode(split($"genre", "[|]"))).show 
+-------+---------+---------+ 
|movieId|movieName| genre| 
+-------+---------+---------+ 
|  1| example1| action| 
|  1| example1| thriller| 
|  1| example1| romance| 
|  2| example2|fantastic| 
|  2| example2| action| 
+-------+---------+---------+ 
0

आप कई पंक्तियों में सरणी explode कर सकते हैं। udf का उपयोग करके आप pipe delimited string को array में परिवर्तित कर सकते हैं। नीचे स्केला

val data = Seq(("1", "example1", "action|thriller|romance"), 
    ("2", "example2", "fantastic|action")).toDF("movieId","movieName", "genre") 

में कोड परिवर्तित genrecolumnArray करने के लिए सरल UDF समारोह का उपयोग कर

val stringtoArray = udf((genre : String) => {genre.split('|')}) 

और से के रूप में

data.withColumn("genre", explode(stringtoArray($"genre"))).show 
संबंधित मुद्दे

 संबंधित मुद्दे