如何连接两个Spark数据帧并操作它们的共享列?

2024-09-30 09:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个这样的数据帧:

+--+-----------+
|id|some_string|
+--+-----------+
| a|        foo|
| b|        bar|
| c|        egg|
| d|        fog|
+--+-----------+

还有这个:

+--+-----------+
|id|some_string|
+--+-----------+
| a|        hoi|
| b|        hei|
| c|        hai|
| e|        hui|
+--+-----------+

我想加入他们,像这样:

+--+-----------+
|id|some_string|
+--+-----------+
| a|     foohoi|
| b|     barhei|
| c|     egghai|
| d|        fog|
| e|        hui|
+--+-----------+

因此,来自第一个数据帧的列some_string与来自第二个数据帧的列some_string相连。如果我正在使用

df_join = df1.join(df2,on='id',how='outer')

它会回来的

+--+-----------+-----------+
|id|some_string|some_string|
+--+-----------+-----------+
| a|        foo|        hoi|
| b|        bar|        hei|
| c|        egg|        hai|
| d|        fog|       null|
| e|       null|        hui|
+--+-----------+-----------+

有什么办法吗?你知道吗


Tags: 数据idstringfooeggbarsomenull
2条回答

考虑到要执行外部联接,可以尝试以下操作:

from pyspark.sql.functions import concat, col, lit, when


df_join= df1.join(df2,on='id',how='outer').when(isnull(df1.some_string1), ''). when(isnull(df2.some_string2),'').withColumn('new_column',concat(col('some_string1'),lit(''),col('some_string2'))).select('id','new_column')

(请注意,some_string1和2是指df1和df2数据帧中的some_string列。我建议您用不同的名称来命名它们,而不是用一些\u字符串来命名相同的名称,这样您就可以调用它们了)

您需要使用^{}来实现适当的连接。除此之外,您使用outerjoin的方式几乎是正确的。你知道吗

您需要检查这两列中是否有人是^{}^{},然后执行^{}。你知道吗

from pyspark.sql.functions import col, when, concat
df1 = sqlContext.createDataFrame([('a','foo'),('b','bar'),('c','egg'),('d','fog')],['id','some_string'])
df2 = sqlContext.createDataFrame([('a','hoi'),('b','hei'),('c','hai'),('e','hui')],['id','some_string'])
df_outer_join=df1.join(df2.withColumnRenamed('some_string','some_string_x'), ['id'], how='outer')
df_outer_join.show()
+ -+     -+      -+
| id|some_string|some_string_x|
+ -+     -+      -+
|  e|       null|          hui|
|  d|        fog|         null|
|  c|        egg|          hai|
|  b|        bar|          hei|
|  a|        foo|          hoi|
+ -+     -+      -+
df_outer_join = df_outer_join.withColumn('some_string_concat',
                                         when(col('some_string').isNotNull() & col('some_string_x').isNotNull(),concat(col('some_string'),col('some_string_x')))
                                         .when(col('some_string').isNull() & col('some_string_x').isNotNull(),col('some_string_x'))
                                         .when(col('some_string').isNotNull() & col('some_string_x').isNull(),col('some_string')))\
                              .drop('some_string','some_string_x')


df_outer_join.show()
+ -+         +
| id|some_string_concat|
+ -+         +
|  e|               hui|
|  d|               fog|
|  c|            egghai|
|  b|            barhei|
|  a|            foohoi|
+ -+         +

相关问题 更多 >

    热门问题