How to slice a pyspark dataframe in two row-wise

后端 未结 5 583
走了就别回头了
走了就别回头了 2020-12-09 18:58

I am working in Databricks.

I have a dataframe which contains 500 rows, I would like to create two dataframes on containing 100 rows and the other containing the rem

5条回答
  •  余生分开走
    2020-12-09 19:35

    Initially I misunderstood and thought you wanted to slice the columns. If you want to select a subset of rows, one method is to create an index column using monotonically_increasing_id(). From the docs:

    The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive.

    You can use this ID to sort the dataframe and subset it using limit() to ensure you get exactly the rows you want.

    For example:

    import pyspark.sql.functions as f
    import string
    
    # create a dummy df with 500 rows and 2 columns
    N = 500
    numbers = [i%26 for i in range(N)]
    letters = [string.ascii_uppercase[n] for n in numbers]
    
    df = sqlCtx.createDataFrame(
        zip(numbers, letters),
        ('numbers', 'letters')
    )
    
    # add an index column
    df = df.withColumn('index', f.monotonically_increasing_id())
    
    # sort ascending and take first 100 rows for df1
    df1 = df.sort('index').limit(100)
    
    # sort descending and take 400 rows for df2
    df2 = df.sort('index', ascending=False).limit(400)
    

    Just to verify that this did what you wanted:

    df1.count()
    #100
    df2.count()
    #400
    

    Also we can verify that the index column doesn't overlap:

    df1.select(f.min('index').alias('min'), f.max('index').alias('max')).show()
    #+---+---+
    #|min|max|
    #+---+---+
    #|  0| 99|
    #+---+---+
    
    df2.select(f.min('index').alias('min'), f.max('index').alias('max')).show()
    #+---+----------+
    #|min|       max|
    #+---+----------+
    #|100|8589934841|
    #+---+----------+
    

提交回复
热议问题