2017-12-29 6 views
0

I 다음 점화 2.2 DataFrame 및 스칼라 2.11.8 가지고 G1G2 :행 정보를 열로 변환하는 방법은 무엇입니까?

df = sqlCtx.createDataFrame(
    [(560,9410,"web","G1",0,5), 
    (290,1430,"web","G1",0,3), 
    (470,1370,"web","G2",0,18), 
    (290,1430,"web","G2",0,5), 
    (290,1430,"mob","G2",1,2)], 
    ["event_id","person_id","channel","group","num1","num2"] 
) 

group 두 개의 값을 가질 수있다 : 여기

+--------+---------+-------+-------+----+-------+ 
|event_id|person_id|channel| group|num1| num2| 
+--------+---------+-------+-------+----+-------+ 
|  560|  9410| web|  G1| 0|  5| 
|  290|  1430| web|  G1| 0|  3| 
|  470|  1370| web|  G2| 0|  18| 
|  290|  1430| web|  G2| 0|  5| 
|  290|  1430| mob|  G2| 1|  2| 
+--------+---------+-------+-------+----+-------+ 

스칼라에 상응 DataFrame이고 . 나는 다음과 같이 새 열에 열 group의 이러한 값을 변환해야합니다

+--------+---------+-------+--------+-------+--------+-------+ 
|event_id|person_id|channel| num1_G1|num2_G1| num1_G2|num2_G2| 
+--------+---------+-------+--------+-------+--------+-------+ 
|  560|  9410| web|  0|  5|  0|  0| 
|  290|  1430| web|  0|  3|  0|  0| 
|  470|  1370| web|  0|  0|  0|  18| 
|  290|  1430| web|  0|  0|  0|  5| 
|  290|  1430| mob|  0|  0|  1|  2| 
+--------+---------+-------+--------+-------+--------+-------+ 

내가 어떻게 할 수 있습니까? 스파크에서 선회

스칼라 버전 할 때 우리가 집계 함수를 사용해야합니다 (내가 집계하지 않고 PIVOT 을 수행 할 수있는 방법을 찾을 수 없습니다 적어도)

+0

가능한 중복을 [ Spark RDD 및/또는 Spark DataFrames에서 데이터 재구성/피벗 (https://stackoverflow.com/questions/30260015/reshaping-pivoting-data-in-spark-rdd-and-or-spark-dataframes) –

답변

3

AFAIK :의

scala> df.groupBy("event_id","person_id","channel") 
     .pivot("group") 
     .agg(max("num1") as "num1", max("num2") as "num2") 
     .na.fill(0) 
     .show 
+--------+---------+-------+-------+-------+-------+-------+ 
|event_id|person_id|channel|G1_num1|G1_num2|G2_num1|G2_num2| 
+--------+---------+-------+-------+-------+-------+-------+ 
|  560|  9410| web|  0|  5|  0|  0| 
|  290|  1430| web|  0|  3|  0|  5| 
|  470|  1370| web|  0|  0|  0|  18| 
|  290|  1430| mob|  0|  0|  1|  2| 
+--------+---------+-------+-------+-------+-------+-------+ 
관련 문제