python - 如何计算 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()
我知道我可以对每一列都这样做,并将结果粘合在一起。我想知道是否有更好的方法来做到这一点。
解决方案
您可以使用窗口函数来实现:
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|
+-----+-----+-----+
推荐阅读
- java - 将用户输入的名称与存储在名称数组中的所有名称进行比较
- dictionary - 立方体贴图/帧缓冲问题
- swift - 如何在 Xcode Playground 的右侧栏中创建我的类型的自定义表示?
- node.js - 无法将角度更新到版本 6
- git - 如何在所有分支中克隆 git 存储库到特定时间?
- android - 上传到Play商店后无法使用linkedIn登录,(直接在发布apk中工作,而不是从Play商店)
- python - 如何在熊猫中进行左外连接排除
- azure - Azure 环境变量
- sql - 将 count() 后的结果分组为 SQL Server 中每个组的单行
- debugging - 是否可以在 PyDev 脚本中设置断点?