2017-11-22 2 views
4

Spark 2.2.0 및 Scala 2.11.8에서 다음 DataFrame을 보유하고 있습니다.각 행에 대해 열에서 특정 요소를 추출하는 방법은 무엇입니까?

+----------+-------------+ 
|item  | other_items | 
+----------+-------------+ 
| 111  | 444   | 
| 222  | 444   | 
| 444  | 111   | 

그래서, 기본적으로, 나는 각 행에 대해 other_items에서 처음 item를 추출해야합니다

+----------+-------------------------------+ 
|item  |  other_items   | 
+----------+-------------------------------+ 
| 111  |[[444,1.0],[333,0.5],[666,0.4]]| 
| 222  |[[444,1.0],[333,0.5]]   | 
| 333  |[]        | 
| 444  |[[111,2.0],[555,0.5],[777,0.2]]| 

나는 다음과 같은 DataFrame을 싶어. 또한 빈 배열 []이있는 행을 other_products에 무시해야합니다.

어떻게하면됩니까?

이 방법을 시도했지만 예상 한 결과를 얻지 못했습니다. 이와 같이

|-- item: string (nullable = true) 
|-- other_items: array (nullable = true) 
| |-- element: struct (containsNull = true) 
| | |-- _1: string (nullable = true) 
| | |-- _2: double (nullable = true) 

답변

1

:

result = df.withColumn("other_items",$"other_items"(0)) 

printScheme 다음 출력 부여 제는 ($"other_items"(0))은 어레이의 첫 번째 요소를 선택 apply

val df = Seq(
    ("111", Seq(("111", 1.0), ("333", 0.5), ("666", 0.4))), ("333", Seq()) 
).toDF("item", "other_items") 


df.select($"item", $"other_items"(0)("_1").alias("other_items")) 
    .na.drop(Seq("other_items")).show 

를 제 apply (_("_1")) selects_1 필드이고, na.drop은필드를 제거합니다.빈 배열에 의해 도입되었습니다.

+----+-----------+ 
|item|other_items| 
+----+-----------+ 
| 111|  111| 
+----+-----------+ 
관련 문제