資料框被提取到臨時表中,以繪制每個時間單位(1 天)的資料密度:
val dailySummariesDf =
getDFFromJdbcSource(SparkSession.builder().appName("test").master("local").getOrCreate(), s"SELECT * FROM values WHERE time > '2020-06-06' and devicename='Voltage' limit 100000000")
.persist(StorageLevel.MEMORY_ONLY_SER)
.groupBy($"digital_twin_id", window($"time", "1 day")).count().as("count")
.withColumn("windowstart", col("window.start"))
.withColumn("windowstartlong", unix_timestamp(col("window.start")))
.orderBy("windowstart")
dailySummariesDf.
registerTempTable("bank")
然后我用%sql處理器繪制它
%sql
select windowstart, count
from bank
和
%sql
select windowstartlong, count
from bank
我得到的如下所示:

所以,我的期望是在這張圖中有空白,因為有幾天根本沒有資料。但相反,我看到它被密集地繪制,10 月的天數在 8 月之后繪制,沒有顯示 9 月的差距。
如何強制這些圖形顯示間隙并考慮實際的 X 軸值?
uj5u.com熱心網友回復:
實際上,按window列對資料集進行分組不會為這些間隔內不包含任何原始行的間隔生成任何行。
我能想到的一種處理方法是添加一堆假行(“手動填充原始資料集中的空白”),然后才應用groupBy/window. 對于您的情況,可以通過創建一個包含您感興趣范圍內所有日期的簡單的單列資料集,然后將其加入原始資料集來完成。
這是我的快速嘗試:
import spark.implicits._
import org.apache.spark.sql.types._
// Define sample data
val df = Seq(("a","2021-12-01"),
("b","2021-12-01"),
("c","2021-12-01"),
("a","2021-12-02"),
("b","2021-12-17")
).toDF("c","d").withColumn("d",to_timestamp($"d"))
// Define a dummy dataframe for the range 12/01/2021 - 12/30/2021
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
val start = DateTime.parse("2021-12-01",DateTimeFormat.forPattern("yyyy-MM-dd")).getMillis/1000
val end = start 30*24*60*60
val temp = spark.range(start,end,24*60*60).toDF().withColumn("tc",to_timestamp($"id".cast(TimestampType))).drop($"id")
// Fill the gaps in original dataframe
val nogaps = temp.join(df, temp.col("tc") === df.col("d"), "left")
// Aggregate counts by a tumbling 1-day window
val result = nogaps.groupBy(window($"tc","1 day","1 day","5 hours")).agg(sum(when($"c".isNotNull,1).otherwise(0)).as("count"))
result.withColumn("windowstart",to_date(col("window.start"))).select("windowstart","count").orderBy("windowstart").show(false)
----------- -----
|windowstart|count|
----------- -----
|2021-12-01 |3 |
|2021-12-02 |1 |
|2021-12-03 |0 |
|2021-12-04 |0 |
|2021-12-05 |0 |
|2021-12-06 |0 |
|2021-12-07 |0 |
|2021-12-08 |0 |
|2021-12-09 |0 |
|2021-12-10 |0 |
|2021-12-11 |0 |
|2021-12-12 |0 |
|2021-12-13 |0 |
|2021-12-14 |0 |
|2021-12-15 |0 |
|2021-12-16 |0 |
|2021-12-17 |1 |
|2021-12-18 |0 |
|2021-12-19 |0 |
|2021-12-20 |0 |
----------- -----
僅用于說明目的:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387355.html
