我有两个Pyspark数据帧(DF1和DF2)。我想检查DF2中的城市列中是否有DF1中的城市,如果是,则从DF2中返回国家名称,并创建一个新的数据框DF3,其中包含Sl.No,City和Country。
DF1
Sl.No City
1个
2 b
2 c
4天
5 e
DF2
乡村城市
瓦
b
X d,e
DF3
Sl.No City Country
1瓦
2 b V
3 c V
4天
5 e X
答案 0 :(得分:1)
这可以通过爆炸来实现
import pyspark.sql.functions as F
l1 = [(1, 'a', ), (2, 'b', ), (3, 'c'), (4, 'd'), (5, 'e')]
df1 = sqlContext.createDataFrame(l1, ['sino','city'])
#df1.show()
l1 = [('W', ['a'] ), ('V', ['b','c'] ), ('X', ['d', 'e'])]
df2 = sqlContext.createDataFrame(l1, ['ctry','cities'])
#df2.show()
df2 = df2.withColumn('cityName', F.explode('cities'))
df3 = df1.join(df2, df1.city == df2.cityName).drop('cities', 'cityName')
df3.show()
+----+----+----+
|sino|city|ctry|
+----+----+----+
| 1| a| W|
| 3| c| V|
| 5| e| X|
| 2| b| V|
| 4| d| X|
+----+----+----+