Scikit Learn's train_test_split is a good one. It will split both numpy arrays and dataframes.

from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size=0.2)
Answer from o-90 on Stack Overflow
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ pandas โ€บ python-pandas-data-frame-exercise-67.php
Pandas: Split a given DataFrame into two random subsets - w3resource
Write a Pandas program to randomly divide a DataFrame into two parts and then export each subset to separate CSV files. Write a Pandas program to split a DataFrame into two random groups and then compute the mean of a numeric column in each group.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ divide-a-pandas-dataframe-randomly-in-a-given-ratio
Divide a Pandas DataFrame randomly in a given ratio | GeeksforGeeks
October 25, 2021 - Pandas is one of those packages and makes importing and analyzing data much easier.Pandas dataframe.div() is used to find the floating division of the dataframe and other ... When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement.
Discussions

python - How do I create test and train samples from one dataframe with pandas? - Stack Overflow
I have a fairly large dataset in ... into two random samples (80% and 20%) for training and testing. ... Scikit Learn's train_test_split is a good one. It will split both numpy arrays and dataframes. from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.2) ... Sign up to request clarification or add additional context in comments. ... Btw, it does return a Pandas Dataframe ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Random shuffle and split Pandas Dataframe for training/validation data
nvm - easier than I thought. use sklearn's train_test_split More on reddit.com
๐ŸŒ r/learnpython
1
0
September 15, 2021
python - How to randomly split a DataFrame into several smaller DataFrames? - Stack Overflow
It will return random permutations of a split of the dataframe. ... Save this answer. ... Show activity on this post. I wanted a way to do this efficiently with arbitrary user defined ratios, without using other external libs, randomization before splitting into smaller frames and landed at the following. Copyfrom itertools import accumulate, chain, pairwise from typing import Iterator, List import pandas ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Randomly Split Dataframe into smaller chunks based on multiple (and similar) string conditions (rows can only used once) - Stack Overflow
I have a data frame with 800 items (rows), and each row is located in a different area. The areas are: Allston, Boston, Brighton, Fenway, Brookline, Cambridge, Newton. Example Pandas Dataframe: ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 18, 2021
๐ŸŒ
Skytowner
skytowner.com โ€บ explore โ€บ randomly_splitting_dataframe_into_multiple_dataframes_of_equal_size_in_pandas
Randomly splitting DataFrame into multiple DataFrames of equal size in Pandas
To randomly split a DataFrame into multiple DataFrames of equal size in Pandas, shuffle the rows using sample(~) method and then call NumPy's arraysplit(~) method.
๐ŸŒ
Dask
docs.dask.org โ€บ en โ€บ stable โ€บ generated โ€บ dask.dataframe.DataFrame.random_split.html
dask.dataframe.DataFrame.random_split โ€” Dask documentation
If int or None create a new RandomState with this as the seed. Otherwise draw from the passed RandomState. ... If set to True, the dataframe is shuffled (within partition) before the split.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ random shuffle and split pandas dataframe for training/validation data
r/learnpython on Reddit: Random shuffle and split Pandas Dataframe for training/validation data
September 15, 2021 -

I have a dataframe of labeled data for training an NLP algorithm. I want to randomly shuffle the dataframe and then split it into 75% training data and 25% validation data.

Can someone point me in the right direction?

For shuffling it looks like I can do

labeled_df = labeled_df.sample(frac=1)

But not sure how to go about splitting the dataframe into two based on the 75% to 25% ratio. Any help is appreciated.

๐ŸŒ
YouTube
youtube.com โ€บ watch
Python Pandas Tutorial (Tips and Tricks):- Split Data-Frame in two random subsets - YouTube
In this video, we will learn (work) on split data frame in two random subsets using Python Panda along with some tips and tricks. Subscribe to the channel an...
Published ย  May 6, 2020
Top answer
1 of 4
38

Use np.array_split

shuffled = df.sample(frac=1)
result = np.array_split(shuffled, 5)  

df.sample(frac=1) shuffle the rows of df. Then use np.array_split split it into parts that have equal size.

It gives you:

for part in result:
    print(part,'\n')
    movie_id  1  2  4  5  6  7  8  9  10  11  12  borda
5          6  5  0  0  0  0  0  0  5   0   0   0     10
4          5  3  0  0  0  0  0  0  0   0   0   0      3
7          8  1  0  0  0  4  5  0  0   0   4   0     14
16        17  3  0  0  4  0  0  0  0   0   0   0      7
22        23  4  0  0  0  4  3  0  0   5   0   0     16 

    movie_id  1  2  4  5  6  7  8  9  10  11  12  borda
13        14  5  4  0  0  5  0  0  0   0   0   0     14
14        15  5  0  0  0  3  0  0  0   0   5   5     18
21        22  4  0  0  0  3  5  5  0   5   4   0     26
1          2  3  0  0  3  0  0  0  0   0   0   0      6
20        21  1  0  0  3  3  0  0  0   0   0   0      7 

    movie_id  1  2  4  5  6  7  8  9  10  11  12  borda
10        11  2  0  4  0  0  3  3  0   4   2   0     18
9         10  3  2  0  0  0  4  0  0   0   0   0      9
11        12  5  0  0  0  4  5  0  0   5   2   0     21
8          9  5  0  0  0  4  5  0  0   4   5   0     23
12        13  5  4  0  0  2  0  0  0   3   0   0     14 

    movie_id  1  2  4  5  6  7  8  9  10  11  12  borda
18        19  5  3  0  0  4  0  0  0   0   0   0     12
3          4  3  0  0  0  0  5  0  0   4   0   5     17
0          1  5  4  0  4  4  0  0  0   4   0   0     21
23        24  3  0  0  4  0  0  0  0   0   3   0     10
6          7  4  0  0  0  2  5  3  4   4   0   0     22 

    movie_id  1  2  4  5  6  7  8  9  10  11  12  borda
17        18  4  0  0  0  0  0  0  0   0   0   0      4
2          3  4  0  0  0  0  0  0  0   0   0   0      4
15        16  5  0  0  0  0  0  0  0   4   0   0      9
19        20  4  0  0  0  0  0  0  0   0   0   0      4 
2 of 4
2

A simple demo:

df = pd.DataFrame({"movie_id": np.arange(1, 25),
          "borda": np.random.randint(1, 25, size=(24,))})
n_split = 5
# the indices used to select parts from dataframe
ixs = np.arange(df.shape[0])
np.random.shuffle(ixs)
# np.split cannot work when there is no equal division
# so we need to find out the split points ourself
# we need (n_split-1) split points
split_points = [i*df.shape[0]//n_split for i in range(1, n_split)]
# use these indices to select the part we want
for ix in np.split(ixs, split_points):
    print(df.iloc[ix])

The result:

    borda  movie_id
8       3         9
10      2        11
22     14        23
7      14         8

    borda  movie_id
0      16         1
20      4        21
17     15        18
15      1        16
6       6         7

    borda  movie_id
9       9        10
19      4        20
5       1         6
16     23        17
21     20        22

    borda  movie_id
11     24        12
23      5        24
1      22         2
12      7        13
18     15        19

    borda  movie_id
3      11         4
14     10        15
2       6         3
4       7         5
13     21        14
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ divide-a-dataframe-in-a-ratio
Divide a DataFrame in a ratio
November 2, 2023 - The sample() method provides more control over the splitting process. It uses the frac parameter to specify the fraction and random_state for reproducible results ? dataframe.sample(frac=fraction, random_state=seed_value) import pandas as pd # Create sample data data = pd.DataFrame({ 'Letters': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'Number': [1, 2, 3, 4, 5, 6, 7, 8] }) print("Original DataFrame:") print(data) # Split into 50-50 using sample() train_data = data.sample(frac=0.5, random_state=42) test_data = data.drop(train_data.index) print(f"\nFirst 50% of data:") print(train_data) print(f"\nRemaining 50% of data:") print(test_data)
๐ŸŒ
Medium
medium.com โ€บ @AIWatson โ€บ how-to-split-a-dataset-into-two-random-subsets-using-python-pandas-4a527f2cd82a
How to Split a Dataset into Training and Testing Subsets using Python Pandas | by Charles Xia | Medium
September 7, 2021 - How to Split a Dataset into Training and Testing Subsets using Python Pandas This story will show you a method to split a dataset into two random subsets. This application is most common for โ€ฆ
๐ŸŒ
Untitled Publication
elisa.hashnode.dev โ€บ split-a-dataframe
Split a Pandas Dataframe in Python - Elisa's Blog - Hashnode
September 29, 2021 - split the dataframe into two parts: its first N rows (or a percentage of the number of rows) and the rest; split it randomly into two parts, by a number of rows or percentage. As example data, I will use my Spotify streaming history during some ...
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ pandas โ€บ how to split pandas dataframe?
How to Split Pandas DataFrame? - Spark By {Examples}
December 6, 2024 - You can split the Pandas DataFrame based on rows or columns by using Pandas.DataFrame.iloc[] attribute, groupby().get_group(), sample() functions. It
๐ŸŒ
datagy
datagy.io โ€บ home โ€บ pandas tutorials โ€บ pandas dataframes โ€บ python: split a pandas dataframe
Python: Split a Pandas Dataframe โ€ข datagy
December 16, 2022 - Learn how to split a Pandas dataframe in Python. Split a dataframe by column value, by position, and by random values.
Top answer
1 of 1
1

Here's code for this specific case. I don't think it can be generalized much.

The idea is from the areas that are allowed in group C, sample 0.1 * 800 = 80 of them and mark them as belonging to group C. Then from the unmarked rows that have areas allowed in group B, select 240 of them and mark them as belonging to group B. All the rest must be in group A.

import pandas as pd
import random

allowed = {
    'A':"Allston Boston Brighton Fenway Brookline Cambridge Newton".split(),
    'B':"Allston Boston Brighton Fenway".split(),
    'C':"Boston Brighton Fenway".split()
}

weight = {
    'A':0.6,
    'B':0.3,
    'C':0.1
}

# create random areas that meet the requirements 10% group C, 30% group B and 60% group A
rows = []
for area in random.choices(list(weight.keys()), weights=weight.values(), k=800):
    rows.append(random.choice(allowed[area]))

# create a dummy data frame
df = pd.DataFrame({'areas':rows,
                   'price':[random.randrange(1000, 5000) for _ in range(len(rows))]})

# add a column for the group, set to '' to indicate unassigned
df['group'] = ['']*len(rows)

for group in 'CBA':
    # Select rows that are not assigned to a group and that have areas that are
    # allowed for the current group. Then randomly sample the selected rows.
    xs = df[(df.group=='') & df['areas'].isin(allowed[group])].sample(n=int(len(rows)*weight[group]))

    # Mark the sampled rows with the group
    df.loc[xs.index,'group'] = group

    # this just to see what's happening
    print(group, len(xs))
    print(df.head())
    print()

The end result is the DataFrame has a column 'group' with a randomly assigned value according to the given constrains.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ split-pandas-dataframe-by-rows
Split Pandas Dataframe by Rows - GeeksforGeeks
November 30, 2023 - Let's see how can we convert a column to row name/index in Pandas.ร‚ Create a dataframe first with dict of lists.ร‚ Python3 # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", " ... In Pandas, it is possible to select rows randomly from a DataFrame with different methods.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49116070 โ€บ randomly-split-dataframe-by-group โ€บ 49116554
python 3.x - randomly split DataFrame by group? - Stack Overflow
I have a DataFrame where multiple rows share group_id values (very large number of groups). Is there an elegant way to randomly split this data into training and test data in a way that the train...