首页 > 解决方案 > 如何计算 pyspark 数据框中的每个分类变量在多列中的频率?

问题描述

我想计算列中每个类别的频率,并用频率计数替换列中的值。我想为 pyspark 数据框的 pyspark 中的多个列执行此操作。

例如,考虑以下数据框:

+-------+-------+-------+  
| col_1 | col_2 | col_3 |
+-------+-------+-------+  
|   a   |   f   |   g   |  
|   c   |   e   |   a   |  
|   a   |   d   |   g   |  
|   a   |   d   |   g   |  
|   b   |   f   |   b   |  
|   c   |   d   |   g   |  
|   b   |   d   |   c   |  
|   a   |   d   |   g   |  
|   b   |   f   |   g   |  
+-------+-------+-------+  

我想将此 pyspark 数据框转换为以下内容:

+-------+-------+-------+  
| col_1 | col_2 | col_3 |
+-------+-------+-------+ 
|   4   |   3   |   6   |
|   2   |   1   |   1   |
|   4   |   5   |   6   |
|   4   |   5   |   6   |
|   3   |   2   |   1   |
|   2   |   5   |   6   |
|   3   |   5   |   1   |
|   4   |   5   |   6   |
|   3   |   2   |   6   |
+-------+-------+-------+  

我有以下代码:

spark = SparkSession.builder.getOrCreate()

df = spark.read.parquet(data)
df.show()

+-------+-------+-------+
| col_1 | col_2 | col_3 |
+-------+-------+-------+
|   a   |   f   |   g   |
|   c   |   e   |   a   |
|   a   |   d   |   g   |
|   a   |   d   |   g   |
|   b   |   f   |   b   |
|   c   |   d   |   g   |
|   b   |   d   |   c   |
|   a   |   d   |   g   |
|   b   |   f   |   g   |
+-------+-------+-------+

我可以使用以下代码使用 for 循环计算每列的频率:

df.groupby('col_1').count().toDF('category', 'count').show()

我知道我可以对每一列都这样做,并将结果粘合在一起。我想知道是否有更好的方法来做到这一点。

标签: pythonpyspark

解决方案


您可以使用窗口函数来实现:

import pyspark.sql.functions as F
from pyspark.sql import Window

l = [
(   'a'   ,   'f'   ,   'g'   ),
(   'c'   ,   'e'   ,   'a'   ),
(   'a'   ,   'd'   ,   'g'   ),
(   'a'   ,   'd'   ,   'g'   ),
(   'b'   ,   'f'   ,   'b'   ),
(   'c'   ,   'd'   ,   'g'   ),
(   'b'   ,   'd'   ,   'c'   ),
(   'a'   ,   'd'   ,   'g'   ),
(   'b'   ,   'f'   ,   'g'  )
]

columns = ['col_1', 'col_2','col_3']

df=spark.createDataFrame(l, columns)


for column in columns:
    df = df.withColumn(column, F.count(column).over(Window.partitionBy(column)))

df.show()

输出:

+-----+-----+-----+ 
|col_1|col_2|col_3| 
+-----+-----+-----+ 
|    4|    3|    6| 
|    3|    3|    6| 
|    4|    5|    6| 
|    4|    5|    6| 
|    4|    5|    6| 
|    2|    5|    6| 
|    3|    5|    1| 
|    3|    3|    1| 
|    2|    1|    1|
+-----+-----+-----+

推荐阅读