Py火花连接在管道分离柱上



我有两个要连接的数据帧。catch是其中一个表具有以管道分隔的字符串,其中一个值是我想要连接的值。我在Pyspark怎么样。下面是一个例子表A有

+-------+--------------------+
|id     |      name          |
+-------+--------------------+
| 613760|123|test|test2      |
| 613740|456|ABC             |
| 598946|OMG|567             | 

表B有

+-------+--------------------+
|join_id|           prod_type|                           
+-------+--------------------+
| 123   |Direct De           |
| 456   |Direct              |
| 567   |In                  | 

预期结果-当表A的管道分隔ID与表B的值匹配时,连接表A和表B。例如TableA.id-613760,名称有123|test,我想用表B的联接id 123联接,同样是456和567。

结果表

+--------------------+-------+
|      name          |join_Id|
+-------+------------+-------+
|123|test|test2      |123    |
|456|ABC             |456    |
|OMG|567             |567    |

有人能帮我解决这个问题吗。我是pyspark的新手,我正在学习

要解决您的问题,您需要:

  • split那些"管道分隔字符串">
  • 然后将这些值分解成分开的行。posexplode会帮你做的http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.posexplode

  • 从那里"内部连接"和

  • 最后,一个"选择"就完成了剩下的任务

请参阅下面的代码:

import pyspark.sql.functions as f
#First create the dataframes to test solution
table_A = spark.createDataFrame([(613760, '123|test|test2' ), (613740, '456|ABC'), (598946, 'OMG|567' )], ["id", "name"])
# +-------+--------------------+
# |id     |      name          |
# +-------+--------------------+
# | 613760|123|test|test2      |
# | 613740|456|ABC             |
# | 598946|OMG|567             | 
table_B = spark.createDataFrame([('123', 'Direct De' ), ('456', 'Direct'), ('567', 'In' )], ["join_id", "prod_type"])
# +-------+--------------------+
# |join_id|           prod_type|                           
# +-------+--------------------+
# | 123   |Direct De           |
# | 456   |Direct              |
# | 567   |In                  | 
result = table_A 
.select(
'name',
f.posexplode(f.split(f.col('name'),'|')).alias('pos', 'join_id')) 
.join(table_B, on='join_id', how='inner') 
.select('name', 'join_id')
result.show(10, False)
# +--------------+-------+
# |name          |join_id|
# +--------------+-------+
# |123|test|test2|123    |
# |456|ABC       |456    |
# |OMG|567       |567    |
# +--------------+-------+

希望能奏效。随着你在Pyspark的不断进步。我建议您完成pyspark.sql.functions中的功能,这将使您的技能更上一层楼。

最新更新