Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Delete the first three rows of a DataFrame in Pandas
To delete the first three rows of a DataFrame in Pandas, we can use the iloc[] indexer to slice the DataFrame starting from the fourth row (index 3).
Using iloc[] to Delete First Three Rows
The iloc[] method allows positional indexing. By using df.iloc[3:], we select all rows starting from index 3 onwards ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
print("Input DataFrame:")
print(df)
print()
# Delete first 3 rows
df = df.iloc[3:]
print("After deleting the first 3 rows:")
print(df)
Input DataFrame: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 7 5 5 5 0 1 1 6 5 4 9 7 2 7 3 After deleting the first 3 rows: x y z 3 0 1 1 4 7 5 5 5 0 1 1 6 5 4 9 7 2 7 3
Alternative Method Using drop()
You can also use the drop() method to delete specific row indices ?
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
print("Original DataFrame:")
print(df)
print()
# Delete first 3 rows using drop()
df_dropped = df.drop([0, 1, 2])
print("After dropping first 3 rows:")
print(df_dropped)
Original DataFrame: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 7 5 5 5 0 1 1 6 5 4 9 7 2 7 3 After dropping first 3 rows: x y z 3 0 1 1 4 7 5 5 5 0 1 1 6 5 4 9 7 2 7 3
Resetting the Index
After deleting rows, you might want to reset the index to start from 0 ?
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0, 7, 0, 5, 2],
"y": [4, 7, 5, 1, 5, 1, 4, 7],
"z": [9, 3, 5, 1, 5, 1, 9, 3]
}
)
# Delete first 3 rows and reset index
df_reset = df.iloc[3:].reset_index(drop=True)
print("After deleting rows and resetting index:")
print(df_reset)
After deleting rows and resetting index: x y z 0 0 1 1 1 7 5 5 2 0 1 1 3 5 4 9 4 2 7 3
Conclusion
Use df.iloc[3:] for simple row slicing or df.drop([0, 1, 2]) for explicit row removal. Add reset_index(drop=True) if you need continuous indexing starting from 0.
Advertisements
