gpt4 book ai didi

python - 在 pyspark 数据帧的其余列中搜索 column1 中的值

转载 作者:行者123 更新时间:2023-12-01 08:15:12 25 4
gpt4 key购买 nike

假设有一个以下形式的 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行名称,列名称)?例如:

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},即唯一的

最佳答案

是的,您可以利用 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:一个 bool 表达式,如果该表达式的值包含在参数的计算值中,则该表达式的计算结果为 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 列等...或您尝试返回的任何内容。该功能可以轻松更改以搜索更多列。希望这有帮助!

关于python - 在 pyspark 数据帧的其余列中搜索 column1 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55031126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com