【问题标题】:Spark dataframe add Missing ValuesSpark 数据框添加缺失值
【发布时间】:2016-12-13 12:14:46
【问题描述】:

我有以下格式的数据框。我想为每个客户添加空行来缺少时间戳。

+-------------+----------+------+----+----+
| 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 个)时间段。 我想出了一种方法来创建一个包含 2 列(Customer_id,Timeslot)和(1 M x 360 行)的数据框,并与原始数据框进行左外连接。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: sql apache-spark pyspark apache-spark-sql spark-dataframe


    【解决方案1】:

    您可以将其表示为 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;
    

    注意事项:

    • 您可能应该将其放入另一个数据框中。
    • 您可能有包含可用客户和/或时间段的表格。使用这些而不是子查询。

    【讨论】:

      【解决方案2】:

      我认为可以使用 gordon linoff 的答案,但是您可以添加以下内容,因为您说有数百万客户并且您正在加入他们。

      为 TimeSlot 使用计数表??因为它可能会提供更好的性能。 更多可用性请参考以下链接

      http://www.sqlservercentral.com/articles/T-SQL/62867/

      我认为你应该使用分区或行号函数来划分你的列 customerid 并根据一些分区值选择客户。例如,只需选择行号值,然后与计数表交叉连接。它可以提高你的表现。

      【讨论】:

        猜你喜欢
        • 2013-02-15
        • 1970-01-01
        • 2022-01-13
        • 2020-08-22
        • 2018-03-02
        • 2014-03-29
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多