Python 2.7 缺少值的数据透视
我有一个带有以下简单模式的Python 2.7 缺少值的数据透视,python-2.7,apache-spark,pivot,pyspark,Python 2.7,Apache Spark,Pivot,Pyspark,我有一个带有以下简单模式的数据框: root |-- amount: double (nullable = true) |-- Date: timestamp (nullable = true) 我试图查看每天和每小时的金额总和,比如: +---+--------+--------+ ... +--------+ |day| 0| 1| | 23| +---+--------+--------+ ... +--------+ |148| 306
数据框
:
root
|-- amount: double (nullable = true)
|-- Date: timestamp (nullable = true)
我试图查看每天和每小时的金额总和,比如:
+---+--------+--------+ ... +--------+
|day| 0| 1| | 23|
+---+--------+--------+ ... +--------+
|148| 306.0| 106.0| | 0.0|
|243| 1906.0| 50.0| | 1.0|
| 31| 866.0| 100.0| | 0.0|
+---+--------+--------+ ... +--------+
首先,我添加了一列hour
,然后我按天分组,并按小时旋转。然而,我有一个例外,这可能与几个小时的销售缺货有关。这就是我试图解决的问题,但我还没有意识到如何解决
(df.withColumn("hour", hour("date"))
.groupBy(dayofyear("date").alias("day"))
.pivot("hour")
.sum("amount").show())
例外情况的摘录
AnalysisException:中缺少u'解析属性日期#3972
日#5367,小时#5354,运算符中的金额#5437!总数的
[dayofyear(日期#3972为日期))],[dayofyear(日期#3972为日期)
日期)为第5367天,第一个数据透视(小时5354,总和(金额)5437,0,1,2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22,23,0,0)作为u轴u sum(amount)作为sum(amount)#5487];'
问题未解决
day
列。您可以在groupBy
子句之外创建它,以解决以下问题:
df = (sc
.parallelize([
(1.0, "2016-03-30 01:00:00"), (30.2, "2015-01-02 03:00:02")])
.toDF(["amount", "Date"])
.withColumn("Date", col("Date").cast("timestamp"))
.withColumn("hour", hour("date")))
with_day = df.withColumn("day", dayofyear("Date"))
with_day.groupBy("day").pivot("hour", range(0, 24)).sum("amount")
轴的值
参数是可选的,但建议使用