从 Pyspark DataFrame 中的选定行获取特定字段 [英] Getting specific field from chosen Row in Pyspark DataFrame

查看:66
本文介绍了从 Pyspark DataFrame 中的选定行获取特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 pyspark 从 JSON 文件构建的 Spark DataFrame

I have a Spark DataFrame built through pyspark from a JSON file as

sc = SparkContext()
sqlc = SQLContext(sc)

users_df = sqlc.read.json('users.json')

现在,我想访问一个 chosen_user 数据,这是它的 _id 字段.我可以

Now, I want to access a chosen_user data, where this is its _id field. I can do

print users_df[users_df._id == chosen_user].show()

这给了我用户的完整行.但是假设我只想要 Row 中的一个特定字段,比如用户性别,我如何获得它?

and this gives me the full Row of the user. But suppose I just want one specific field in the Row, say the user gender, how would I obtain it?

推荐答案

只需过滤和选择:

result = users_df.where(users_df._id == chosen_user).select("gender")

或使用 col

from pyspark.sql.functions import col

result = users_df.where(col("_id") == chosen_user).select(col("gender"))

最后,PySpark Row 只是一个带有一些扩展的 tuple,所以你可以例如 flatMap:

Finally PySpark Row is just a tuple with some extensions so you can for example flatMap:

result.rdd.flatMap(list).first()

map 像这样:

result.rdd.map(lambda x: x.gender).first()

这篇关于从 Pyspark DataFrame 中的选定行获取特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆