如何划分数据帧行';将每个值按行';s pyspark中的总和(数据规范化)?
我有一个用户偏好的数据框:如何划分数据帧行';将每个值按行';s 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 | 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..|
+-------+------+-------+-------+
非常感谢,它工作得非常好!请问如何将行中的每个值除以行中的最大值?将
rowsum
行替换为magest=f.magest(*(df[x]表示cols中的x))
whereimport pyspark.sql.functions as f
。它不知何故找到了错误的最大值,因此在除以后,我得到了一些大于1的值,这意味着原始值除以较小的值。它看起来是这样的:| 100 | 0.0 | 1.3333333333 | 0.6666666666 |
但是我认为不应该有大于1的值,因为原始值中的最大值除以最大值
应该给PySpark一个新的1
。我可以问一下select语句中的*
是什么意思吗?*
与spark无关。这是一种python语法,用于将多个参数分散到函数调用中。
# 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|
+-------+-----+------------------+------------------+