pyspark:使用一个df中的一行过滤并选择另一个df

mitkmikd  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(461)

我尝试在一个pysparkDataframe中迭代行,并使用每行中的值对第二个pysparkDataframe执行操作(filter,select),然后绑定所有结果。也许这是最好的例证:
df1型

id   name   which_col
1    John   col1
2    Jane   col3
3    Bob    col2
4    Barb   col1

df2型

name  col1  col2  col3
Bob   78    43    54
Bob   23    65    34
Bob   12    98    75
John  45    54    54
John  75    43    12
Jane  24    45    21
...

我想对df1中的每一行执行的步骤是:
取'name'中的值并用它来过滤df2(例如,对于第1行,将df2只过滤到“john”行)
然后根据“which\u col”中的df1值选择相应的df2列(例如,对于john,选择df2中的col1,而对于jane,则选择col3)。
对df1的每一行重复上述步骤
将所有结果绑定到一个最终df中。

dy2hfwbg

dy2hfwbg1#

您可以在加入之前取消PIVOT(堆栈)df2:

result = df1.join(
    df2.selectExpr(
        'name',
        'stack(3, ' + ', '.join(["'%s', %s" % (c, c) for c in df2.columns[1:]]) + ') as (which_col, value)'
    ), 
    ['name', 'which_col'], 
    'left'
)

result.show()
+----+---------+---+-----+
|name|which_col| id|value|
+----+---------+---+-----+
|John|     col1|  1|   75|
|John|     col1|  1|   45|
|Jane|     col3|  2|   21|
| Bob|     col2|  3|   98|
| Bob|     col2|  3|   65|
| Bob|     col2|  3|   43|
|Barb|     col1|  4| null|
+----+---------+---+-----+

相关问题