How to delete all rows in a dataframe?

Given a pandas dataframe, we have to delete all rows in a dataframe.
Submitted by Pranit Sharma, on October 13, 2022

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 we are given a DataFrame with multiple columns and any values associated with these columns.

We need to delete all the rows from this DataFrame, for this purpose, we can use df.drop method and we can set the index label as the parameter.

But instead of completely deleting all the rows by using pandas.DataFrame.drop() method, we will play with the indices of rows and columns, we will look after our DataFrame with columns only.

Deleting all rows in a dataframe

To delete all rows in a dataframe, we will store the DataFrame with no row in another variable and we can do this by using the 0th to 0th index inside DataFrame.

Let us understand with the help of an example,

Python program to delete all rows in a dataframe

# Importing pandas package
import pandas as pd

# Importing calendar
import calendar

# Creating a Dictionary
d = {
    'Name':['Ram','Shyam','Seeta','Geeta'],
    'Age':[20,21,23,20],
    'Salary':[20000,23000,19000,40000],
    'Department':['IT','Sales','Production','Manager'],
    'Location':['Delhi','Mumbai','Chennai','Pune']
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Accessing only columns of DataFrame
res = df[0:0]

# Display modified DataFrame
print("Modified DataFrame:\n",res)

Output

The output of the above program is:

Example: Delete all rows in a dataframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.