【发布时间】:2015-11-05 21:23:33
【问题描述】:
我正在尝试使用 Spark DataFrame API 将我的数据框从长到宽重塑。数据集是学生提问的问题和答案的集合。这是一个庞大的数据集,Q(Question) 和 A(Answer) 大约在 1 到 50000 之间。我想收集所有可能的 Q*A 对并使用它们来构建列。如果学生对问题 1 的回答为 1,我们将值 1 分配给第 1_1 列。否则,我们给它一个 0。数据集已经在 S_ID、Q、A 上进行了重复数据删除。
在 R 中,我可以在库 reshape2 中简单地使用 dcast,但我不知道如何使用 Spark。我在下面的链接中找到了旋转的解决方案,但它需要固定数量的不同 Q*A 对。 http://rajasoftware.net/index.php/database/91446/scala-apache-spark-pivot-dataframes-pivot-spark-dataframe
我还尝试使用用户定义的函数连接 Q 和 A 并且它们应用交叉表但是,即使到目前为止我只在示例数据文件上测试我的代码,我仍然从控制台收到以下错误 -
The maximum limit of le6 pairs have been collected, which may not be all of the pairs.
Please try reducing the amount of distinct items in your columns.
原始数据:
S_ID、Q、A
1, 1, 1
1、2、2
1、3、3
2、1、1
2、2、3
2、3、4
2、4、5
=> 长宽变换后:
S_ID、QA_1_1、QA_2_2、QA_3_3、QA_2_3、QA_3_4、QA_4_5
1, 1, 1, 1, 0, 0, 0
2, 1, 0, 0, 1, 1, 1
R code.
library(dplyr); library(reshape2);
df1 <- df %>% group_by(S_ID, Q, A) %>% filter(row_number()==1) %>% mutate(temp=1)
df1 %>% dcast(S_ID ~ Q + A, value.var="temp", fill=0)
Spark code.
val fnConcatenate = udf((x: String, y: String) => {"QA_"+ x +"_" + y})
df1 = df.distinct.withColumn("QA", fnConcatenate($"Q", $"A"))
df2 = stat.crosstab("S_ID", "QA")
任何想法将不胜感激。
【问题讨论】:
-
Q(Question) 和 A(Answer) 大约在 1 到 50000 之间 - 这是否意味着您有 50000 或 50000^2 个 QA 对/列?
-
@zero323 Q 和 A 都有数万个值。对于这对,我相信我们的数量不到十倍。
标签: r scala apache-spark apache-spark-sql