【问题标题】:How to join(Merge) two SparkDataFrame in SparkR and keep one of the common columns如何在 SparkR 中加入(合并)两个 SparkDataFrame 并保留其中一个公共列
【发布时间】:2017-01-14 16:48:10
【问题描述】:

我有以下 Spark DataFrame:

aps=data.frame(agent=c('a','b','c','d','a','a','a','b','c','a','b'),product=c('P1','P2','P3','P4','P1','P1','P2','P2','P2','P3','P3'),
      sale_amount=c(1000,2000,3000,4000,1000,1000,2000,2000,2000,3000,3000))

RDD_aps=createDataFrame(sqlContext,agent_product_sale)


   agent product sale_amount
1      a      P1        1000
2      b      P2        2000
3      c      P3        3000
4      d      P4        4000
5      a      P1        1000
6      a      P1        1000
7      a      P2        2000
8      b      P2        2000
9      c      P2        2000
10     a      P3        3000
11     b      P3        3000

和 percent=data.frame(agent=c('a','b','c'),percent=c(0.2 ,0.5,1.0))

agent  percent
  a      0.2
  b      0.5
  c      1.0

我需要加入(合并)两个数据框,以便我可以为每个代理分配一个百分比 像这样的输出:

   agent product sale_amount     percent
1      d      P4        4000          NA
2      c      P3        3000         1.0
3      c      P2        2000         1.0
4      b      P2        2000         0.5
5      b      P2        2000         0.5
6      b      P3        3000         0.5
7      a      P1        1000         0.2
8      a      P1        1000         0.2
9      a      P1        1000         0.2
10     a      P2        2000         0.2
11     a      P3        3000         0.2

我已经试过了:

     joined_aps=join(RDD_aps,percent,RDD_aps$agent==percent$agent,"left_outer")

但它从百分比数据框中添加了一个新的第二个“代理”列,我不想要重复的列。

我也试过了:

merged=merge(RDD_aps,percent, by = "agent",all.x=TRUE)

这个还添加了“agent_y”列,但我只想在(RDD_aps 的代理列)中有一个代理列

【问题讨论】:

    标签: r apache-spark spark-dataframe sparkr


    【解决方案1】:

    我想我看到有人通过在 SO 上的某处使用 join 来阻止生成“_x”和“_y”变量,但我找不到那个帖子。在我的操作中,我个人更喜欢merge...我认为这对我来说更容易,而且我喜欢能够使用all.x=TRUE/FALSEall.y=TRUE/FALSE 参数在左/右/内/外/等连接之间切换。我仍然得到烦人的(但对验证有用)_x_y 列,但我使用类似于以下示例的代码修复了这些列:

    df1<- data.frame(person=c("Bob", "Jane", "John", "Liz"), favoriteColor=c("Blue", "Green", "Black", "White"))
    df2<- data.frame(person=c("Bob", "Jane", "John", "Liz"), age=c(10,20,30,40))
    
    sdf1<- SparkR::createDataFrame(df1)
    sdf2<- SparkR::createDataFrame(df2)
    
    sdf<- SparkR::merge(sdf1, sdf2, by.x="person", by.y="person", all.x=FALSE, all.y=FALSE) # Inner join...all.x/y not needed
    colnames(sdf) # person_x and person_y are now present...to be fixed here
    
    colnames(sdf)<- gsub(pattern= "_x",replacement = "", colnames(sdf))
    
    col_names_sdf_subset<- colnames(sdf)[!(colnames(sdf) %in% colnames(sdf)[grep("_y", colnames(sdf))])]
    
    sdf<- sdf %>% SparkR::select(col_names_sdf_subset) 
    
    colnames(sdf)
    View(head(sdf, num=20L))
    

    【讨论】:

      猜你喜欢
      • 2013-09-18
      • 2021-03-11
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      相关资源
      最近更新 更多