2017-04-13 68 views
1

我有一個DataFrame爲A,如:如何計算日期的最大值爲每列上的數據幀與pyspark

+---+---+---+---+----------+ 
|key| c1| c2| c3|  date| 
+---+---+---+---+----------+ 
| k1| -1| 0| -1|2015-04-28| 
| k1| 1| -1| 1|2015-07-28| 
| k1| 1| 1| 1|2015-10-28| 
| k2| -1| 0| 1|2015-04-28| 
| k2| -1| 1| -1|2015-07-28| 
| k2| 1| -1| 0|2015-10-28| 
+---+---+---+---+----------+ 

這些代碼來創建答:

data = [('k1', '-1', '0', '-1','2015-04-28'), 
    ('k1', '1', '-1', '1', '2015-07-28'), 
    ('k1', '1', '1', '1', '2015-10-28'), 
    ('k2', '-1', '0', '1', '2015-04-28'), 
    ('k2', '-1', '1', '-1', '2015-07-28'), 
    ('k2', '1', '-1', '0', '2015-10-28')] 
A = spark.createDataFrame(data, ['key', 'c1', 'c2','c3','date']) 
A = A.withColumn('date',A.date.cast('date')) 

我想最大日期的某些列從c1到c5的值等於1或-1。 B的預期的結果:

+---+----------+----------+----------+----------+----------+----------+ 
|key|  c1_1|  c2_1|  c3_1|  c1_-1|  c2_-1|  c3_-1| 
+---+----------+----------+----------+----------+----------+----------+ 
| k1|2015-10-28|2015-10-28|2015-10-28|2015-04-28|2015-07-28|2015-04-28| 
| k2|2015-10-28|2015-07-28|2015-04-28|2015-07-28|2015-10-28|2015-07-28| 
+---+----------+----------+----------+----------+----------+----------+ 

我的預覽的解決方案是通過使用樞軸操作來分別計算從C1-C2的列,然後再加入新創建的那些DateFrames。但是,在我的情況下,專欄太多了,我遇到了表演的問題。所以,我希望得到其他解決方案來替代DataFrame的加入。

回答

2

首先melt the DataFrame

value_vars = ["c1", "c2", "c3"] 
a_long = melt(A, id_vars=["key", "date"], value_vars=value_vars) 

下降的零點:

without_zeros = a_long.where(col("value") != 0) 

合併變量的值:

from pyspark.sql.functions import concat_ws 

combined = without_zeros.withColumn(
    "cs", concat_ws("_", col("variable"), col("value"))) 

最後樞軸:

from pyspark.sql.functions import max 

(combined 
    .groupBy("key") 
    .pivot("cs", ["{}_{}".format(c, i) for c in value_vars for i in [-1, 1]]) 
    .agg(max("date"))) 

結果是:

+---+----------+----------+----------+----------+----------+----------+ 
|key|  c1_-1|  c1_1|  c2_-1|  c2_1|  c3_-1|  c3_1| 
+---+----------+----------+----------+----------+----------+----------+ 
| k2|2015-07-28|2015-10-28|2015-10-28|2015-07-28|2015-07-28|2015-04-28| 
| k1|2015-04-28|2015-10-28|2015-07-28|2015-10-28|2015-04-28|2015-10-28| 
+---+----------+----------+----------+----------+----------+----------+ 
相關問題