Home »
Python »
Python Programs
Pandas: Split dataframe into two dataframes at a specific row
Learn how to split pandas dataframe into two dataframes at a specific row?
By Pranit Sharma Last updated : October 06, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose that we are given a dataframe containing 10 rows and we need to split this dataframe into two containing 1st five rows in the first dataframe and the last 5 rows in another dataframe.
Splitting dataframe into two dataframes at a specific row
For this purpose, we will use the iloc property. i in iloc stands for 'index'. This is also a data selection method but here, we need to pass the proper index as a parameter to select the required row or column. Indexes are nothing but the integer value ranging from 0 to n-1 which represents the number of rows or columns. We can perform various operations using iloc property. Inside iloc, the index value of the row comes first followed by the number of columns.
Let us understand with the help of an example,
Python program to split pandas dataframe into two dataframes at a specific row
# Import pandas
import pandas as pd
# Creating a dataframe
df = pd.DataFrame({
'A': [1,2,3,4,5,6,7,8,9,10],
'B':['a','b','c','d','e','f','g','h','i','j']
})
# Display original dataframe
print("Original DataFrame:\n",df,"\n")
# Splitting dataframe into two dataframes
df1 = df.iloc[:5]
df2 = df.iloc[5:]
# Display new dataframes
print("DataFrame 1:\n",df1,"\n")
print("DataFrame 2:\n",df2,"\n")
Output
The output of the above program is:
Python Pandas Programs »