首页 > 解决方案 > 在 pyspark 数据框的其余列中搜索 column1 中的值

问题描述

假设有一个 pyspark 数据框的形式:

id  col1  col2 col3 col4
------------------------
as1  4    10    4    6
as2  6    3     6    1
as3  6    0     2    1
as4  8    8     6    1
as5  9    6     6    9

有没有办法在 pyspark 数据帧的col 2-4中搜索col1中的值并返回(id row name, column name)?例如:

In col1, 4 is found in (as1, col3)
In col1, 6 is found in (as2,col3),(as1,col4),(as4, col3) (as5,col3)
In col1, 8 is found in (as4,col2)
In col1, 9 is found in (as5,col4)

提示:假设 col1 将是一个集合 {4,6,8,9} 即唯一

标签: pythonsearchpyspark

解决方案


是的,您可以利用 Spark SQL.isin运算符。

让我们首先在您的示例中创建 DataFrame

第 1 部分 - 创建 DataFrame

cSchema = StructType([StructField("id", IntegerType()),\
StructField("col1", IntegerType()),\
StructField("col2", IntegerType()),\
StructField("col3", IntegerType()),\
StructField("col4", IntegerType())])


test_data = [[1,4,10,4,6],[2,6,3,6,1],[3,6,0,2,1],[4,8,8,6,1],[5,9,6,6,9]]


df = spark.createDataFrame(test_data,schema=cSchema)

df.show()

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  1|   4|  10|   4|   6|
|  2|   6|   3|   6|   1|
|  3|   6|   0|   2|   1|
|  4|   8|   8|   6|   1|
|  5|   9|   6|   6|   9|
+---+----+----+----+----+

第 2 部分 - 搜索匹配值的功能

isin:一个布尔表达式,如果该表达式的值包含在参数的评估值中,则该表达式的评估结果为 true。 http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html

def search(col1,col3):
    col1_list = df.select(col1).rdd\
    .map(lambda x: x[0]).collect()
    search_results = df[df[col3].isin(col1_list)]
    return search_results

search_results.show()

+---+----+----+----+----+
| id|col1|col2|col3|col4|
+---+----+----+----+----+
|  1|   4|  10|   4|   6|
|  2|   6|   3|   6|   1|
|  4|   8|   8|   6|   1|
|  5|   9|   6|   6|   9|
+---+----+----+----+----+

这应该会引导您朝着正确的方向前进。您可以仅选择 Id 列等。或者您尝试返回的任何内容。可以轻松更改该功能以使用更多列进行搜索。希望这可以帮助!


推荐阅读