2017-09-29 7 views
0

저는 Pyspark에서 새로운입니다. 나는 '테이블 A'와 '테이블 B'를 가지고 있으며 '테이블 C'를 얻으려면 모두 가입해야합니다. 누구든지 도와 줄 수 있나요? 내가 가입하는 방법을 모르는Pyspark Join Tables

내가 DataFrames을 사용하고

... 그 모두 함께 올바른 방법으로 테이블 ...

표 A :

+--+----------+-----+  
|id|year_month| qt | 
+--+----------+-----+ 
| 1| 2015-05| 190 | 
| 2| 2015-06| 390 | 
+--+----------+-----+ 

표 B :

+---------+-----+ 
year_month| sem | 
+---------+-----+ 
| 2016-01| 1 | 
| 2015-02| 1 | 
| 2015-03| 1 | 
| 2016-04| 1 | 
| 2015-05| 1 | 
| 2015-06| 1 | 
| 2016-07| 2 | 
| 2015-08| 2 | 
| 2015-09| 2 | 
| 2016-10| 2 | 
| 2015-11| 2 | 
| 2015-12| 2 | 
+---------+-----+ 
,

표 C : (가) 행을 추가 또한 열을 추가하고 가입 ...

+--+----------+-----+-----+  
|id|year_month| qt | sem | 
+--+----------+-----+-----+ 
| 1| 2015-05 | 0 | 1 | 
| 1| 2016-01 | 0 | 1 | 
| 1| 2015-02 | 0 | 1 | 
| 1| 2015-03 | 0 | 1 | 
| 1| 2016-04 | 0 | 1 | 
| 1| 2015-05 | 190 | 1 | 
| 1| 2015-06 | 0 | 1 | 
| 1| 2016-07 | 0 | 2 | 
| 1| 2015-08 | 0 | 2 | 
| 1| 2015-09 | 0 | 2 | 
| 1| 2016-10 | 0 | 2 | 
| 1| 2015-11 | 0 | 2 | 
| 1| 2015-12 | 0 | 2 | 
| 2| 2015-05 | 0 | 1 | 
| 2| 2016-01 | 0 | 1 | 
| 2| 2015-02 | 0 | 1 | 
| 2| 2015-03 | 0 | 1 | 
| 2| 2016-04 | 0 | 1 | 
| 2| 2015-05 | 0 | 1 | 
| 2| 2015-06 | 390 | 1 | 
| 2| 2016-07 | 0 | 2 | 
| 2| 2015-08 | 0 | 2 | 
| 2| 2015-09 | 0 | 2 | 
| 2| 2016-10 | 0 | 2 | 
| 2| 2015-11 | 0 | 2 | 
| 2| 2015-12 | 0 | 2 | 
+--+----------+-----+-----+ 

코드 :

from pyspark import HiveContext 
sqlContext = HiveContext(sc) 

lA = [(1,"2015-05",190),(2,"2015-06",390)] 
tableA = sqlContext.createDataFrame(lA, ["id","year_month","qt"]) 
tableA.show() 

lB = [("2016-01",1),("2015-02",1),("2015-03",1),("2016-04",1), 
     ("2015-05",1),("2015-06",1),("2016-07",2),("2015-08",2), 
     ("2015-09",2),("2016-10",2),("2015-11",2),("2015-12",2)] 
tableB = sqlContext.createDataFrame(lB,["year_month","sem"]) 
tableB.show() 

답변

0

그것은하지 정말 join 더 카티 제품 (cross join) 입니다

스파크 2

import pyspark.sql.functions as psf 
tableA.crossJoin(tableB)\ 
    .withColumn(
     "qt", 
     psf.when(tableB.year_month == tableA.year_month, psf.col("qt")).otherwise(0))\ 
    .drop(tableA.year_month) 

스파크 1.6

tableA.join(tableB)\ 
    .withColumn(
     "qt", 
     psf.when(tableB.year_month == tableA.year_month, psf.col("qt")).otherwise(0))\ 
    .drop(tableA.year_month) 

+---+---+----------+---+ 
| id| qt|year_month|sem| 
+---+---+----------+---+ 
| 1| 0| 2015-02| 1| 
| 1| 0| 2015-03| 1| 
| 1|190| 2015-05| 1| 
| 1| 0| 2015-06| 1| 
| 1| 0| 2016-01| 1| 
| 1| 0| 2016-04| 1| 
| 1| 0| 2015-08| 2| 
| 1| 0| 2015-09| 2| 
| 1| 0| 2015-11| 2| 
| 1| 0| 2015-12| 2| 
| 1| 0| 2016-07| 2| 
| 1| 0| 2016-10| 2| 
| 2| 0| 2015-02| 1| 
| 2| 0| 2015-03| 1| 
| 2| 0| 2015-05| 1| 
| 2|390| 2015-06| 1| 
| 2| 0| 2016-01| 1| 
| 2| 0| 2016-04| 1| 
| 2| 0| 2015-08| 2| 
| 2| 0| 2015-09| 2| 
| 2| 0| 2015-11| 2| 
| 2| 0| 2015-12| 2| 
| 2| 0| 2016-07| 2| 
| 2| 0| 2016-10| 2| 
+---+---+----------+---+