【问题标题】:Forming a new spark dataframe with some selected set of rows from a existing dataframe使用现有数据框中的某些选定行集形成新的火花数据框
【发布时间】:2018-04-09 08:59:57
【问题描述】:

我有一个具有 10^8 行数的 spark 数据框 df。我在该数据框上添加了一个列作为我想用作主键的 rowId。 我已经用

的命令做了同样的事情

df.withColumn("rowId", monotonically_increasing_id())

现在,我想从该数据框中选择一个新的数据框,其中包含一些选定的行数,其索引以列表的形式为我所知。 如果有人可以帮助我用列表中选定的行数形成一个新的数据框,那对我会有帮助。

【问题讨论】:

    标签: python hadoop pyspark spark-dataframe apache-zeppelin


    【解决方案1】:

    我不确定我是否了解您的用例。 monotonically_increasing_id() 保证唯一的 id,但不保证 id 从 0 或 1 开始或数字是连续的。在下面的示例中,我对数据框进行了重新分区,以表明 monotonically_increasing_id() 不能保证连续的 id。无论如何,假设您在驱动程序内存中有一个您想要的索引列表,您可以在添加索引列后简单地加入您的数据框。

    //Create a sample dataframe and add rowId column. 
    //Note that you may see 0,1,2 as rowIds if you dont repartition. 
    
    val df = List("A","B","C").toDF.repartition(5).withColumn("rowId", monotonically_increasing_id())
    df.show()
    +-----+------------+
    |value|       rowId|
    +-----+------------+
    |    A|  8589934592|
    |    B|  8589934593|
    |    C| 34359738368|
    +-----+------------+
    
    //[Option 1] to join with indexes we need to add index column to our DataFrame. Assuming your indexes align with sorted rowId
    val w = org.apache.spark.sql.expressions.Window.orderBy("rowId")
    val result = df.withColumn("index", row_number().over(w) - 1)
    
    //here is our indexes. let convert it to Dataframe to prepare for join
    val indexes = List(0, 2).toDF
    //finally join
    result.join(indexes, result("index") === indexes("value")).show()
    +-----+-----------+-----+-----+
    |value|      rowId|index|value|
    +-----+-----------+-----+-----+
    |    A| 8589934592|    0|    0|
    |    C|34359738368|    2|    2|
    +-----+-----------+-----+-----+
    
    
    //[Option 2] if your list is small and can easily be sent to all workers, you can also simply filter
    result.filter(result("index").isin(List(0, 2):_*)).show()
    +-----+-----------+-----+
    |value|      rowId|index|
    +-----+-----------+-----+
    |    A| 8589934592|    0|
    |    C|34359738368|    2|
    +-----+-----------+-----+
    

    【讨论】:

    • 非常感谢你能不能给我pyspark代码,因为我的生产环境是python
    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多