Sql Spark dataframe添加缺少的值
我有一个以下格式的数据帧。我想为每个客户添加缺少时间戳的空行Sql Spark dataframe添加缺少的值,sql,apache-spark,pyspark,apache-spark-sql,spark-dataframe,Sql,Apache Spark,Pyspark,Apache Spark Sql,Spark Dataframe,我有一个以下格式的数据帧。我想为每个客户添加缺少时间戳的空行 +-------------+----------+------+----+----+ | Customer_ID | TimeSlot | A1 | A2 | An | +-------------+----------+------+----+----+ | c1 | 1 | 10.0 | 2 | 3 | | c1 | 2 | 11 | 2 | 4 |
+-------------+----------+------+----+----+
| Customer_ID | TimeSlot | A1 | A2 | An |
+-------------+----------+------+----+----+
| c1 | 1 | 10.0 | 2 | 3 |
| c1 | 2 | 11 | 2 | 4 |
| c1 | 4 | 12 | 3 | 5 |
| c2 | 2 | 13 | 2 | 7 |
| c2 | 3 | 11 | 2 | 2 |
+-------------+----------+------+----+----+
结果表的格式应为
+-------------+----------+------+------+------+
| Customer_ID | TimeSlot | A1 | A2 | An |
+-------------+----------+------+------+------+
| c1 | 1 | 10.0 | 2 | 3 |
| c1 | 2 | 11 | 2 | 4 |
| c1 | 3 | null | null | null |
| c1 | 4 | 12 | 3 | 5 |
| c2 | 1 | null | null | null |
| c2 | 2 | 13 | 2 | 7 |
| c2 | 3 | 11 | 2 | 2 |
| c2 | 4 | null | null | null |
+-------------+----------+------+------+------+
我有100万客户和360个(在上面的示例中仅描述了4个)时段。
我想出了一种方法来创建一个包含两列(Customer_id,Timeslot)和(1m x 360行)的数据帧,并与原始数据帧进行左外连接
有更好的方法吗?您可以将其表示为SQL查询:
select df.customerid, t.timeslot,
t.A1, t.A2, t.An
from (select distinct customerid from df) c cross join
(select distinct timeslot from df) t left join
df
on df.customerid = c.customerid and df.timeslot = t.timeslot;
注:
- 您可能应该将其放入另一个数据帧中
- 您可能有包含可用客户和/或时间段的表。使用这些查询而不是子查询
select df.customerid, t.timeslot,
t.A1, t.A2, t.An
from (select distinct customerid from df) c cross join
(select distinct timeslot from df) t left join
df
on df.customerid = c.customerid and df.timeslot = t.timeslot;
注:
- 您可能应该将其放入另一个数据帧中
- 您可能有包含可用客户和/或时间段的表。使用这些查询而不是子查询
我认为您应该使用分区或行号函数来划分列customerid,并根据某个分区值选择客户。例如,只需选择行号值,然后与理货表交叉连接。它可以提高你的表现 我认为可以使用gordon linoff的答案,但您可以添加以下内容,因为您声明有数以百万计的客户,并且您正在参与其中 使用时隙理货表??因为它可能会有更好的表现。 有关更多实用性,请参考以下链接 我认为您应该使用分区或行号函数来划分列customerid,并根据某个分区值选择客户。例如,只需选择行号值,然后与理货表交叉连接。它可以提高你的表现