pyspark - 如何在pyspark中将数据帧行每个值除以行总和(数据标准化)?

标签 pyspark

我有一个用户偏好的数据框:

+-------+-----+-----+-----+
|user_id|Movie|Music|Books|
+-------+-----+-----+-----+
|   100 |  0  |  1  |  2  |
|   101 |  3  |  1  |  4  |
+-------+---------+-------+

如何1)计算每行(用户)的总和; 2)将每个值除以该总和?所以我得到标准化的偏好值:

+-------+---- -+-------+-------+
|user_id| Movie| Music | Books |
+-------+----- +-------+-------+
|   100 |  0   | 0.33..| 0.66..|
|   101 |0.42..| 0.15..| 0.57..|
+-------+------+-------+-------+

最佳答案

# get column names that need to be normalized
cols = [col for col in df.columns if col != 'user_id']

# sum the columns by row
rowsum = sum([df[x] for x in cols])

# select user_id and normalize other columns by rowsum
df.select('user_id', *((df[x] / rowsum).alias(x) for x in cols)).show()

+-------+-----+------------------+------------------+
|user_id|Movie|             Music|             Books|
+-------+-----+------------------+------------------+
|    100|  0.0|0.3333333333333333|0.6666666666666666|
|    101|0.375|             0.125|               0.5|
+-------+-----+------------------+------------------+

关于pyspark - 如何在pyspark中将数据帧行每个值除以行总和(数据标准化)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63185054/

相关文章:

python - 如何将 PySpark RDD 转换为具有未知列的 Dataframe?

apache-spark - 忽略了 JSON 阅读器中的 Spark 采样选项?

python - 无法 pickle _thread.rlock 对象 Pyspark 向 elasticsearch 发送请求

python - Pyspark 将多个 csv 文件读入数据框(或 RDD?)

if-statement - PySpark:创建新列并根据其他两列的条件进行填充

python - 如何将参数传递给 agg pyspark 函数的字典输入

amazon-s3 - 在 AWS Glue 中将增量数据从 Dynamodb 加载到 S3

amazon-web-services - Pyspark:如何检查s3中是否存在带有通配符的文件路径

python - Spark安装问题-TypeError : an integer is required (got type bytes) - spark-2. 4.5-bin-hadoop2.7, hadoop 2.7.1, python 3.8.2

python - Spark : Pyspark: how to monitor python worker processes