python - 在 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} 即唯一
解决方案
是的,您可以利用 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 列等。或者您尝试返回的任何内容。可以轻松更改该功能以使用更多列进行搜索。希望这可以帮助!
推荐阅读
- php - PHP Regex 模式获取指定的单词
- python - 密码锁程序
- c# - asp.net核心不加载静态文件
- python - 如何从此 python 代码中获得正确的输出?
- youtube-api - YouTube 分析与 YouTube 数据 API 差异
- vim - 让 vim 识别 COOL 语法
- html - 我可以在按钮项目中插入一个按钮,并针对不同的反应进行点击吗?
- sqlite - 编写一个 SQLite 查询,返回所有日期早于某个值的记录
- machine-learning - 如何将由 torchvision.datasets 创建的数据集放在 GPU 中的一次操作中?
- java - Guice 辅助注入 - java.lang.IllegalStateException:zip 文件已关闭