繁体   English   中英

选定列中值的唯一组合计数

[英]Count of unique combinations of values in selected columns

我有一个看起来像这样的 PySpark 数据框:

----------------------------
id    A    B    C 
id1   on   on   on
id1   on   off  on 
id1   on   on   on 
id1   on   on   on 
id1   on   on   off
-----------------------------

我正在寻找一种方法来查找选定列的所有唯一组合并显示它们的计数。 预期输出:

----------------------------
id    A    B    C    count
id1   on   on   on   3
id1   on   off  on   1
id1   on   on   off  1
-----------------------------

我看到有一种方法可以在 Pandas 中进行类似的操作,但我需要 PySpark。

UPD:另外,请注意 A 列和 B 列的唯一组合与 A、B、C 的组合不同。 我想要每一列的所有可能组合。 有没有办法实现它,而不是按一个组合、另一个组合等进行分组和计数? 有超过 10 列。

cube可以做到。 但它会显示所有组合,包括是否未考虑某些列。 因此,您必须在之后进行过滤。

from pyspark.sql import functions as F
df = spark.createDataFrame(
    [('id1', 'on', 'on', 'on'),
     ('id1', 'on', 'off', 'on'), 
     ('id1', 'on', 'on', 'on'), 
     ('id1', 'on', 'on', 'on'), 
     ('id1', 'on', 'on', 'off')],
    ['id', 'A', 'B', 'C'])

df = df.cube(df.columns).count()
df = df.filter(F.forall(F.array(df.columns), lambda x: x.isNotNull()))

df.show()
# +---+---+---+---+-----+
# | id|  A|  B|  C|count|
# +---+---+---+---+-----+
# |id1| on| on| on|    3|
# |id1| on|off| on|    1|
# |id1| on| on|off|    1|
# +---+---+---+---+-----+

这将仅在指定列中计算出现次数:

cols = ['A', 'B']
df = df.cube(cols).count()
df = df.filter(F.forall(F.array(df.columns), lambda x: x.isNotNull()))

df.show()
# +---+---+-----+
# |  A|  B|count|
# +---+---+-----+
# | on|off|    1|
# | on| on|    4|
# +---+---+-----+

解决方案:

df = spark.createDataFrame(
    [
        ("id1", "on","on","on"),  # create your data here, be consistent in the types.
        ("id1", "on","off","on"),
        ("id1", "on","on","on"),
        ("id1", "on","on","on"),
        ("id1", "on","on","off"),
    ],
    ["id", "A" , "B" , "C"]  # add your column names here
)

除了 Cube 功能,我们还有 Rollup 功能。

多维数据集:它采用列列表并将聚合表达式应用于分组列的所有可能组合。

rollup :与cube类似的函数是rollup ,它从左到右计算分层小计。 使用GROUP BY ROLLUP(...)类似于 CUBE,但通过从左到右填充列来分层工作。

from pyspark.sql import functions as F

df = df.rollup(df.columns).count()

df1 = df.na.drop(subset=df.columns)

df1.show()

# ---+---+---+---+-----+
# | id|  A|  B|  C|count|
# +---+---+---+---+-----+
# |id1| on| on|off|    1|
# |id1| on| on| on|    3|
# |id1| on|off| on|    1|
# +---+---+---+---+-----+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM