【问题标题】:Count distinct column values based on condition pyspark根据条件pyspark计算不同的列值
【发布时间】:2020-12-23 21:57:14
【问题描述】:

我有一列有 2 个可能的值:'users' 或 'not_users'

我想要做的是在这些值是“用户”时计算不同的值

这是我正在使用的代码:

output = (df
           .withColumn('week', f.expr('DATE_FORMAT(DATE_SUB(registration_date, 1), "Y-ww")'))
           .groupby('week') 
           .agg(f.countDistinct('customer_id').alias('count_total_users'),
                f.countDistinct('vegetables_customers').alias('count_vegetable_users')   
     
               )
         
          )

display(output)

这是输出(不需要):

Week        count_total_users      count_vegetable_users
2020-40            2345                        2
2020-41            5678                        2
2020-42            3345                        2
2020-43            5689                        2

想要的输出:

Week        count_total_users      count_vegetable_users
2020-40            2345                        457
2020-41            5678                        1987
2020-42            3345                        2308
2020-43            5689                        4000

这个期望的输出应该是它所属列中“用户”值的不同计数。

有什么线索吗?

【问题讨论】:

  • 如果在值为 user 时计算不同的值,您总是得到 1...?
  • 不清楚。如果你也分享一些数据会更好
  • 我的问题是:如何从列中计算“用户”。不是所有的值,只是条件 == 'users' 下的值

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


【解决方案1】:

df2是你想要的结果吗?

df.show()
+----+-----------+--------------------+
|week|customer_id|vegetables_customers|
+----+-----------+--------------------+
|   1|          1|               users|
|   1|          2|           not_users|
|   1|          3|               users|
|   2|          1|           not_users|
|   2|          2|           not_users|
|   2|          3|               users|
+----+-----------+--------------------+

df2 = df.groupBy('week').agg(
    F.countDistinct('customer_id').alias('count_total_users'),
    F.countDistinct(
        F.when(
            F.col('vegetables_customers') == 'users', 
            F.col('customer_id')
        )
    ).alias('count_vegetable_users')
)

df2.show()
+----+-----------------+---------------------+
|week|count_total_users|count_vegetable_users|
+----+-----------------+---------------------+
|   1|                3|                    2|
|   2|                3|                    1|
+----+-----------------+---------------------+

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2018-08-07
    • 2021-08-24
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多