使用pyspark将用户项目评级列表转换为用户项目矩阵

时间:2017-06-16 16:59:27

标签: pandas apache-spark pyspark apache-spark-sql pyspark-sql

这是用户项评级列表的外观,如pandas数据框。

   item_id  rating user_id
0  aaaaaaa       5       X
1  bbbbbbb       2       Y
2  ccccccc       5       Z
3  ddddddd       1       T

这是我如何在pandas中创建用户项目矩阵,它只需要几秒钟的真实数据集(大约500k行):

user_item_matrix = df.pivot(index = 'user_id', columns ='item_id', values = 'rating')

item_id  aaaaaaa  bbbbbbb  ccccccc  ddddddd
user_id                                    
T            NaN      NaN      NaN      1.0
X            5.0      NaN      NaN      NaN
Y            NaN      2.0      NaN      NaN
Z            NaN      NaN      5.0      NaN

我正在尝试这种方法来实现与pyspark数据帧相同的结果。

from pyspark.sql.functions import first

df.groupby('user_id') \
  .pivot('item_id') \
  .agg(first('rating'))

但完成真实数据需要很长时间。是否有更聪明/更快的方法来实现这一目标?基本上我正在尝试从用户项目评级列表构建用户项矩阵。

1 个答案:

答案 0 :(得分:0)

这是一种基于RDD的替代方法。

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    // Configure the cell to show the book's title
    NSManagedObject *book = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = [book valueForKey:@"title"];
}

现在我假设一个用户可能会对多个项目进行评分。在这种情况下,您可能需要根据user_id减少RDD并合并评级。它只是.toDF之前的另一个reduceByKey语句,你应该得到这样的df。

相关问题