内部加入pyspark
inner join in pyspark
我有一个 pyspark 数据框 (df1),它包含 10K 行,数据框看起来像 -
id mobile_no value
1 1111111111 .43
2 2222222222 .54
3 3333333333 .03
4 4444444444 .22
另一个 pyspark 数据框 (df2) 由 100k 条记录组成,看起来像 -
mobile_no gender
912222222222 M
914444444444 M
919999999999 F
915555555555 M
918888888888 F
我想使用 pyspark 进行内部连接,最终数据框看起来像 -
mobile_no value gender
2222222222 .54 M
4444444444 .22 M
mobile_no 的长度在 df2 中是 12,但在 df1 中是 10。我可以加入它,但它的操作成本很高。
对使用 pyspark 有帮助吗?
common_cust = spark.sql("SELECT mobile_number, age \
FROM df1 \
WHERE mobile_number IN (SELECT DISTINCT mobile_number FROM df2)")
一种方法是在 df2
上使用 substring
函数来仅保留最后 10 位数字以获得与 df1
:
中相同的长度
import pyspark.sql.functions as F
ddf2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender').show()
+----------+------+
| mobile_no|gender|
+----------+------+
|2222222222| M|
|4444444444| M|
|9999999999| F|
|5555555555| M|
|8888888888| F|
+----------+------+
然后你只需要做一个内部join
来得到你预期的输出:
common_cust = df1.select('mobile_no', 'value')\
.join( df2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender'),
on=['mobile_no'], how='inner')
common_cust.show()
+----------+-----+------+
| mobile_no|value|gender|
+----------+-----+------+
|2222222222| 0.54| M|
|4444444444| 0.22| M|
+----------+-----+------+
如果你想使用 spark.sql
,我想你可以这样做:
common_cust = spark.sql("""select df1.mobile_no, df1.value, df2.gender
from df1
inner join df2
on df1.mobile_no = substring(df2.mobile_no, 3, 10)""")
我有一个 pyspark 数据框 (df1),它包含 10K 行,数据框看起来像 -
id mobile_no value
1 1111111111 .43
2 2222222222 .54
3 3333333333 .03
4 4444444444 .22
另一个 pyspark 数据框 (df2) 由 100k 条记录组成,看起来像 -
mobile_no gender
912222222222 M
914444444444 M
919999999999 F
915555555555 M
918888888888 F
我想使用 pyspark 进行内部连接,最终数据框看起来像 -
mobile_no value gender
2222222222 .54 M
4444444444 .22 M
mobile_no 的长度在 df2 中是 12,但在 df1 中是 10。我可以加入它,但它的操作成本很高。 对使用 pyspark 有帮助吗?
common_cust = spark.sql("SELECT mobile_number, age \
FROM df1 \
WHERE mobile_number IN (SELECT DISTINCT mobile_number FROM df2)")
一种方法是在 df2
上使用 substring
函数来仅保留最后 10 位数字以获得与 df1
:
import pyspark.sql.functions as F
ddf2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender').show()
+----------+------+
| mobile_no|gender|
+----------+------+
|2222222222| M|
|4444444444| M|
|9999999999| F|
|5555555555| M|
|8888888888| F|
+----------+------+
然后你只需要做一个内部join
来得到你预期的输出:
common_cust = df1.select('mobile_no', 'value')\
.join( df2.select(F.substring('mobile_no', 3, 10).alias('mobile_no'),'gender'),
on=['mobile_no'], how='inner')
common_cust.show()
+----------+-----+------+
| mobile_no|value|gender|
+----------+-----+------+
|2222222222| 0.54| M|
|4444444444| 0.22| M|
+----------+-----+------+
如果你想使用 spark.sql
,我想你可以这样做:
common_cust = spark.sql("""select df1.mobile_no, df1.value, df2.gender
from df1
inner join df2
on df1.mobile_no = substring(df2.mobile_no, 3, 10)""")