【问题标题】:How to use getItem(x, ...) in sparkR and how to subset a particular value in column?如何在 sparkR 中使用 getItem(x, ...) 以及如何对列中的特定值进行子集化?
【发布时间】:2015-12-06 14:10:57
【问题描述】:

我有一个 sparkR 数据框cust_sales,我只需要从cust_id 列中提取值CQ98901282,在R 中我们使用cust_sales$cust_id[3]

我的建议是我们可以使用getItem(x, ...) 来提取,如果可以的话 参数“x”将是列cust_sales$cust_id

  1. 参数“...”中会出现什么
  2. 如果我的建议是错误的,getItem(x, ...) 的用途是什么以及如何在我的示例中使用它。

    +----------+----------+-----------+
    |   cust_id|      date|Total_trans|
    +----------+----------+-----------+
    |CQ98901280|2015-06-06|          1|
    |CQ98901281|2015-05-01|          1|
    |CQ98901282|2015-05-02|          1|
    |CQ98901283|2015-05-03|          1|
    |CQ98901284|2015-04-01|          6|
    |CQ98901285|2015-04-02|          8|
    |CQ98901286|2015-04-03|         13|
    |CQ98901287|2015-04-04|          3|
    |CQ98901288|2015-04-05|          3|
    |CQ98901289|2015-04-08|         16|
    

TIA, 阿伦

【问题讨论】:

    标签: r apache-spark dataframe apache-spark-sql sparkr


    【解决方案1】:

    Spark 数据帧不支持随机行访问,您对 getItem 函数的工作方式有误解。它适用于从地图或数组等非原子字段中提取数据:

    > writeLines('{"foo": [0, 1], "bar": {"x": 3, "y": 4}}', "example.json")
    > df <- SparkR::jsonFile(sqlContext, "example.json")
    > printSchema(df)
    root
     |-- bar: struct (nullable = true)
     |    |-- x: long (nullable = true)
     |    |-- y: long (nullable = true)
     |-- foo: array (nullable = true)
     |    |-- element: long (containsNull = true)
    > select(df, getItem(df$bar, "x"), getItem(df$bar, "y")) %>% head()
      bar[x] bar[y]
    1      3      4
    

    由于某种原因,我无法使其与数组一起使用,而是使用 PySpark

    >>> df = sqlContext.read.json("example.json")
    >>> df.select(df.foo.getItem(0)).show()
    >>> df.select(df.foo.getItem(0), df.foo.getItem(1), df.bar.getItem("x")).show()
    +------+------+------+
    |foo[0]|foo[1]|bar[x]|
    +------+------+------+
    |     0|     1|     3|
    +------+------+------+
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多