[FIXED] split DataFrame into training and testing DataFrame using pyspark

Issue

I have 2038 length of DataFrame, which i want to split it into training and testing DataFrame using PySpark.

My DataFrame looks like this (DataFrame Sample) -

Item Value
1 10
2 2
2 35
1 12
1 16
3 26

I want my DataFrame to Split like this

  • Training DataFrame length - 2008 and
  • Testing DataFrame length - 30

Solution

Since you are requiring the exact number of sample in the training and testing dataset, functions like randomSplit or sampleBy that use fraction or weight is not suitable for your case. If you don't have any performance concern, one of the solutions is using the joining:

from pyspark.sql import SparkSession
from pyspark.sql import functions as func

df = spark\
    .createDataFrame([(str(i),) for i in range(2038)],
                     ['row_index'])
df.show(5, False)

+---------+
|row_index|
+---------+
|0        |
|1        |
|2        |
|3        |
|4        |
+---------+

Then you can use the joining directly:

train_df = df.limit(2000)
test_df = df.join(train_df, on='row_index', how='leftanti')

If you want to do randomization, just add:

train_df = df.orderBy(func.rand()).limit(2000)


Answered By - Jonathan Lam
Answer Checked By - Clifford M. (sql.easybugfix Volunteer)

Related Posts

Post a Comment