Divide a Pandas DataFrame randomly in a given ratio
Divide a Pandas Dataframe task is very useful in case of split a given dataset into train and test data for training and testing purposes in the field of Machine Learning, Artificial Intelligence, etc. Let’s see how to divide the pandas dataframe randomly into given ratios. For this task, We will use Dataframe.sample() and Dataframe.drop() methods of pandas dataframe together.
The Syntax of these functions are as follows –
Syntax: DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)
Return Type: A new object of same type as caller containing n items randomly sampled from the caller object.
Syntax: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)
Return: Dataframe with dropped values.
Example: Now, let’s create a Dataframe:
Example 1: Divide a Dataframe randomly into a 1:1 ratio.
Example 2: Divide a Dataframe randomly into a 3:1 ratio.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course