You could use list comprehension with a little modications your list, l, first.

print(df)

   a  b  c
0  1  1  1
1  2  2  2
2  3  3  3
3  4  4  4
4  5  5  5
5  6  6  6
6  7  7  7
7  8  8  8


l = [2,5,7]
l_mod = [0] + l + [max(l)+1]

list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

Output:

list_of_dfs[0]

   a  b  c
0  1  1  1
1  2  2  2

list_of_dfs[1]

   a  b  c
2  3  3  3
3  4  4  4
4  5  5  5

list_of_dfs[2]

   a  b  c
5  6  6  6
6  7  7  7

list_of_dfs[3]

   a  b  c
7  8  8  8
Answer from Scott Boston on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › split-pandas-dataframe-by-column-index
Split Pandas Dataframe by Column Index - GeeksforGeeks
July 15, 2025 - import pandas as pd dataset = {'toothed': [1, 1, 1, 0, 1, 1, 1, 1, 1, 0], 'hair': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0], 'breathes': [1, 1, 1, 1, 1, 1, 0, 1, 1, 1], 'legs': [1, 1, 0, 1, 1, 1, 0, 0, 1, 1], 'species': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0] } df = pd.DataFrame(dataset) df.head() ... Example 1: Now we would like to separate species columns from the feature columns (toothed, hair, breathes, legs) for this we are going to make use of the iloc[rows, columns] method offered by pandas. Here ':' stands for all the rows and -1 stands for the last column so the below cell is going to take the all the rows and all columns except the last one ('species') as can be seen in the output: ... To split the species column from the rest of the dataset we make you of a similar code except in the cols position instead of padding a slice we pass in an integer value -1.
Discussions

python - Pandas split DataFrame according to indices - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
pandas - split data frame based on integer index - Stack Overflow
In pandas how do I split Series/dataframe into two Series/DataFrames where odd rows in one Series, even rows in different? Right now I am using rng = range(0, n, 2) odd_rows = df.iloc[rng] This is More on stackoverflow.com
🌐 stackoverflow.com
Split pandas dataframe based on first value in row

You can get at the index you need directly without relying on a counter:

# Get index for 2nd occurrence of pattern in 1st column
cutoff = df.loc[(df.index < 40) & (df.iloc[:, 0].str.contains(r'^[4-6][A-z]*[0-9]'))].index[1]

# Using loc, not iloc, because we have the actual index
df1 = df.loc[:cutoff]
df1 = df.loc[cutoff:]

I also added a '^' to your regex, assuming this pattern needs to occur at the start.

More on reddit.com
🌐 r/learnpython
6
9
January 19, 2018
python - Splitting pandas dataframe based on index value - Stack Overflow
For example, the row with the index ... row with index 12 before the filtering happened (even though they are adjacent now). Therefore 61 should be in its own group. But 12 should be in the same group as 1-12 ... Assuming you want to group rows based on whether or not their row indices differ by 1, we can try the following: import pandas as pd import numpy as np # Generate toy data random_data = np.random.random(14) # Create a dataframe with toy ... More on stackoverflow.com
🌐 stackoverflow.com
April 29, 2022
🌐
YouTube
youtube.com › watch
Slice pandas DataFrame by Index in Python (Example) | Split at Particular Row | How to Divide Data - YouTube
How to split a pandas DataFrame at a certain row index position in the Python programming language. More details: https://statisticsglobe.com/slice-pandas-da...
Published   July 6, 2022
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › slice pandas dataframe by index in python (example)
Slice pandas DataFrame by Index in Python | Split & Create Two Subsets
July 22, 2022 - In the next step, we can use this splitting point to extract all rows before this index point: data_upper = data.iloc[:split_point] # Create upper data set print(data_upper) # Print DataFrame of upper rows · After executing the previous syntax the pandas DataFrame subset shown in Table 2 has been created.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.str.split.html
pandas.Series.str.split — pandas 3.0.4 documentation - PyData |
Splits the string in the Series/Index from the beginning, at the specified delimiter string. ... String or regular expression to split on. If not specified, split on whitespace. ... Limit number of splits in output. None, 0 and -1 will be interpreted as return all splits.
🌐
Delft Stack
delftstack.com › home › howto › python pandas › split pandas dataframe
How to Split Pandas DataFrame | Delft Stack
February 2, 2024 - We can specify the rows to be included in each split in the iloc property. [:2,:] represents select the rows up to row with index 2 exclusive (the row with index 2 is not included) and all the columns from the DataFrame. Hence, apprix_df.iloc[:2,:] selects first two rows from the DataFrame apprix_df with index 0 and 1. import pandas as pd apprix_df = pd.DataFrame( { "Name": ["Anish", "Rabindra", "Manish", "Samir", "Binam"], "Post": ["CEO", "CTO", "System Admin", "Consultant", "Engineer"], "Qualification": ["MBA", "MS", "MS", "PhD", "MS"], } ) print("Apprix Team DataFrame:") print(apprix_df, "\
Find elsewhere
🌐
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
🌐
YouTube
youtube.com › watch
How to Split DataFrame Index by Separator and Convert to Columns in Pandas - YouTube
Learn how to effectively split the index of a Pandas DataFrame by a specific separator and transform it into separate columns. Enhance your data manipulation...
Published   April 6, 2025
Views   0
🌐
Reddit
reddit.com › r/learnpython › split pandas dataframe based on first value in row
r/learnpython on Reddit: Split pandas dataframe based on first value in row
January 19, 2018 -

I have a dataframe I need to split in two, where the splitting point is the first value in some row. My df looks like this:

                      0       1         2         3         4
0               6Vfatl2     NaN       NaN          NaN           NaN
1              Name       123456  7.377354  2.000000  6.005613
.......
31           Someone      123486  7.158705  2.333333  7.290309
32              6Vfatl4     NaN       NaN         NaN           NaN
33           Person      123488  6.883334  3.666667  6.764028

I want to split the df between lines 31 and 32 (keeping row 32 as part of the second df). I have looked up some solutions on StackOverflow but none of them seemed to work for this particular problem.

I tried this, but isn't there a better way to do it? (And yes, I am SURE I have to cut before the 40th row):

indices = []
for i in range(40):
    if re.match(r'[4-6][A-z]*[0-9]',df.iloc[i][0]):
        indices.append(i)

df1 = df.iloc[:indices[1]]  #Split dataframe into 2 (per class)
df2 = df.iloc[indices[1]:]

EDIT: Formatting, (temporary) solution

🌐
GeeksforGeeks
geeksforgeeks.org › split-pandas-dataframe-by-rows
Split Pandas Dataframe by Rows - GeeksforGeeks
November 30, 2023 - Difference of two columns in pandas dataframe in Python is carried out by using following methods : Method #1 : Using ” -” operator. Python3 import pandas as pd # Create a DataFrame df1 = { 'Name':['George','Andrea','micheal', 'maggie','Ravi','Xien','Jalpa'], 'score1':[62,47,55,74,32,77,86], 'score2 ... Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we get the index of maximum value in DataFrame column.Observe this dataset first.
🌐
Medium
medium.com › @amit25173 › how-to-split-dataframe-into-chunks-in-pandas-6c1282e31552
How to Split DataFrame into Chunks in Pandas? | by Amit Yadav | Medium
March 6, 2025 - You might be wondering: How do I split a huge DataFrame efficiently without consuming too much memory? Instead of storing all chunks in memory, use an iterator to process chunks one by one. This is perfect for working with massive datasets that don’t fit into RAM. from itertools import islice def chunk_dataframe(df, chunk_size): it = iter(df.index) # Create an iterator over index while chunk := list(islice(it, chunk_size)): # Yield chunks of `chunk_size` yield df.loc[chunk] # Example Usage for i, chunk in enumerate(chunk_dataframe(df, 3)): print(f"Chunk {i+1}:\n", chunk, "\n")
🌐
Python.org
discuss.python.org › python help
Divide each row of a pandas dataframe by index value - Python Help - Discussions on Python.org
January 18, 2023 - Hi, I try to divide each row of a pandas dataframe by its index. I know how to do it, but is there a more concise way? import numpy as np import pandas as pd df = pd.DataFrame({'A': [3,4,5], 'B':[5,6,2], 'C': [7,9,3]}, index = [2,3,4]) df1 = df.copy() df1.loc[:] = np.nan for i in df.index: df1.loc[i, :] = df.loc[i, :]/i
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.Series.str.split.html
pandas.Series.str.split — pandas 2.3.3 documentation - PyData |
Splits the string in the Series/Index from the beginning, at the specified delimiter string. ... String or regular expression to split on. If not specified, split on whitespace. ... Limit number of splits in output. None, 0 and -1 will be interpreted as return all splits.
🌐
Untitled Publication
elisa.hashnode.dev › split-a-dataframe
Split a Pandas Dataframe in Python - Elisa's Blog - Hashnode
September 29, 2021 - So if you have a customized dataset type, it might not be straightforward to use random_split. In that case, or in any other case when you need two (or one!) random parts of a dataframe, you can use the Pandas method sample. We can either specify the number of rows we want in our random sample or the ratio of the original dataframe, respectively with args n or frac: df_1 = df.sample(n=5000) # or: frac=0.9 df_2 = df.loc[~df.index.isin(df_t.index)].reset_index(drop=True) df_1 = df_1.reset_index(drop=True)
Top answer
1 of 3
7

You add reset_index instead df_test1['index1'] = df_test1.index and for clean df add rename_axis - it remove column name place:

df_test1 = df_test.groupby(['code' , 'year', 'week',  'place'])['vl'].sum() \
                  .unstack(fill_value=0) \
                  .reset_index() \
                  .rename_axis(None, axis=1)
print (df_test1)

            code  year  week  region1  region2  region3
0  111.0002.0056  2017    28        0        1        0
1  111.0002.0056  2017    29        1        1        0
2  111.0002.0056  2017    30        0        1        0
3  111.0002.0114  2017    31        0        0        1
4  112.5600.6325  2017    30        0        2        0
5  112.5600.8159  2017    28        0        0        1
6  112.5600.8159  2017    30        0        1        0
7  112.5600.8159  2017    31        0        0        1
8  112.6500.2285  2017    31        0        1        0

Last if necessary change ordering of columns:

#all cols are columns in df_test1
cols = ['code' , 'year', 'week']
df_test1 = df_test1[[x for x in df_test1.columns if x not in cols] + cols]
print (df_test1)
   region1  region2  region3           code  year  week
0        0        1        0  111.0002.0056  2017    28
1        1        1        0  111.0002.0056  2017    29
2        0        1        0  111.0002.0056  2017    30
3        0        0        1  111.0002.0114  2017    31
4        0        2        0  112.5600.6325  2017    30
5        0        0        1  112.5600.8159  2017    28
6        0        1        0  112.5600.8159  2017    30
7        0        0        1  112.5600.8159  2017    31
8        0        1        0  112.6500.2285  2017    31
2 of 3
2

Or you can try this pd.crosstab

df=df.set_index(['code', 'year', 'week','vl'])
df=pd.crosstab(df.index,df.place).reset_index()
df[['code', 'year', 'week','vl']]=df['row_0'].apply(pd.Series).drop('row_0',axis=1)

Out[32]: 
place  region1  region2  region3           code  year  week  vl
0            0        1        0  111.0002.0056  2017    28   1
1            1        1        0  111.0002.0056  2017    29   1
2            0        1        0  111.0002.0056  2017    30   1
3            0        0        1  111.0002.0114  2017    31   1
4            0        2        0  112.5600.6325  2017    30   1
5            0        0        1  112.5600.8159  2017    28   1
6            0        1        0  112.5600.8159  2017    30   1
7            0        0        1  112.5600.8159  2017    31   1
8            0        1        0  112.6500.2285  2017    31   1