【问题标题】:Pyspark DataFrame count occurrences of value of a column in an other columnPyspark DataFrame 计算另一列中某列值的出现次数
【发布时间】:2020-02-11 11:18:50
【问题描述】:

我有一个 Dataframe,其中包含:

+--------------------+--------------------+-------------+
|                 src|                 dst|linkage_count|
+--------------------+--------------------+-------------+
|             abc.com|        _spf.a22.biz|            0|
|             abc.com|     _spf.google.com|            0|
|     _spf.google.com|        _spf.mail.ru|            0|
+--------------------+--------------------+-------------+

现在我想遍历每一行并获取“dst”列的值,并在“src”列中找到该“dst”值的出现次数,并将其添加到“linkage_count”列。所以在这种情况下,结果应该是:

+--------------------+--------------------+-------------+
|                 src|                 dst|linkage_count|
+--------------------+--------------------+-------------+
|             abc.com|        _spf.a22.biz|            0|
|             abc.com|     _spf.google.com|            1|
|     _spf.google.com|        _spf.mail.ru|            0|
+--------------------+--------------------+-------------+

【问题讨论】:

  • linking_count 的最后一行不应该等于 1,因为 _spf 出现在该行的 dst 和 src 中?还是 _spf 对计数不重要?

标签: python dataframe pyspark


【解决方案1】:

使用自联接的一种方式:

df.alias("l").join(df.alias("r"), col("l.dst") == col("r.src"), "left")\
             .groupBy("l.src", "l.dst")\
             .agg((count("r.src") + first("l.linkage_count")).alias("linkage_count"))\
             .show()

我们在dst == src 上使用左连接并计算添加到linkage_count 列的匹配数。

给予:

+---------------+---------------+-------------+
|            src|            dst|linkage_count|
+---------------+---------------+-------------+
|        abc.com|   _spf.a22.biz|            0|
|_spf.google.com|   _spf.mail.ru|            0|
|        abc.com|_spf.google.com|            1|
+---------------+---------------+-------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2023-02-06
    • 2020-02-04
    • 1970-01-01
    • 2021-04-12
    • 2019-03-27
    相关资源
    最近更新 更多