python - 如何从 df.collect() 结果中检索 PySpark 中的特定值?
问题描述
我在 PySparkdf
中有以下 DataFrame。
import pyspark.sql.functions as func
df = spark\
.read \
.format("org.elasticsearch.spark.sql") \
.load("my_index/my_mapping") \
.groupBy(["id", "type"]) \
.agg(
func.count(func.lit(1)).alias("number_occurrences"),
func.countDistinct("host_id").alias("number_hosts")
)
ds = df.collect()
我使用collect
是因为分组和聚合后的数据量总是很小并且适合内存。另外,我需要使用collect
,因为我ds
作为udf
函数的参数传递。该函数collect
返回一个数组。如何对此数组进行以下查询:对于给定的id
and type
,返回number_occurrences
andnumber_hosts
。
例如,假设df
包含以下行:
id type number_occurrences number_hosts
1 xxx 11 3
2 yyy 10 4
完成后df.collect()
,我如何检索number_occurences
和number_hosts
for id
equal to1
和type
equal to xxx
。预期结果是:
number_occurrences = 11
number_hosts = 3
更新:
也许有更优雅的解决方案?
id = 1
type = "xxx"
number_occurrences = 0
number_hosts = 0
for row in ds:
if (row["id"] == id) & (row["type"] == type):
number_occurrences = row["number_occurrences"]
number_hosts = row["number_hosts"]
解决方案
如果您id
是唯一的(应该是 id 的情况),您可以根据 id 对数组进行排序。这只是确保正确的顺序,如果您的 id 是连续的,您可以直接访问记录并将 id 减去 1
test_df = spark.createDataFrame([
(1,"xxx",11,3),(2,"yyyy",10,4),
], ("id","type","number_occurrences","number_hosts"))
id = 1
type = "xxx"
sorted_list = sorted(test_df.collect(), cmp=lambda x,y: cmp(x["id"],y["id"]))
sorted_list[id-1]["number_occurrences"],sorted_list[id-1]["number_hosts"]
结果:
(11, 3)
推荐阅读
- javascript - 如何在输入字段中仅显示一个密码项目符号?
- python-3.x - 服务器无法将消息从一个客户端发送到python套接字编程中的客户端列表
- c# - 如何在客户端的剃须刀文件中下载从控制器返回的 .msg 文件
- visual-studio-extensions - 在 2 个工作区中使用 Visual Studio 扩展
- javascript - JS如何根据另一个值访问特定的数组值
- android - Flutter 返回 Main.dart 屏幕而不是关闭应用程序
- c# - 使用 Revit API(或任何其他方法)获取 Autodesk Docs 本地文件夹
- rstudio - 源窗格在 Rstudio 中显示灰色特殊字符
- javascript - Nuxt Algolia InstantSearch:实现客户端动态获取时的服务端渲染
- python - Discord.py Bot - 如何提及随机用户