【问题标题】:Getting specific field from chosen Row in Pyspark DataFrame从 Pyspark DataFrame 中的选定行获取特定字段
【发布时间】:2016-06-13 17:14:51
【问题描述】:

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

sc = SparkContext()
sqlc = SQLContext(sc)

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

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

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

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

【问题讨论】:

    标签: python apache-spark dataframe pyspark apache-spark-sql


    【解决方案1】:

    只需过滤和选择:

    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

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

    map 类似这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2021-10-16
      • 2021-12-26
      • 1970-01-01
      • 2020-12-17
      • 2019-07-24
      相关资源
      最近更新 更多