Answers for "Data Analytics with Pandas – How to Drop a List of Rows from a Pandas Dataframe"

0

Data Analytics with Pandas – How to Drop a List of Rows from a Pandas Dataframe

import pandas as pd

data = {"product_name":["Keyboard","Mouse", "Monitor", "CPU","CPU", "Speakers",pd.NaT],
        "Unit_Price":[500,200, 5000.235, 10000.550, 10000.550, 250.50,None],
        "No_Of_Units":[5,5, 10, 20, 20, 8,pd.NaT],
        "Available_Quantity":[5,6,10,"Not Available","Not Available", pd.NaT,pd.NaT],
        "Available_Since_Date":['11/5/2021', '4/23/2021', '08/21/2021','09/18/2021','09/18/2021','01/05/2021',pd.NaT]
       }

df = pd.DataFrame(data)

df
=================
df.drop([5,6], axis=0, inplace=True)

df

In this code,

    [5,6] is the index of the rows you want to delete
    axis=0 denotes that rows should be deleted from the dataframe
    inplace=True performs the drop operation in the same dataframe
#######
How to Drop Rows by Index Range in Pandas
df.drop(df.index[2:4], inplace=True)

df
==============
How to Drop All Rows after an Index in Pandas

df = df.iloc[:2]

df

In this code, :2 selects the rows until the index 2.
=================
How to Drop Rows with Multiple Conditions in Pandas

df.drop(df[(df['Unit_Price'] >400) & (df['Unit_Price'] < 600)].index, inplace=True)

df

In this code,

    (df['Unit_Price'] >400) & (df['Unit_Price'] < 600) is the condition to drop the rows.
    df[].index selects the index of rows which passes the condition.
    inplace=True performs the drop operation in the same dataframe rather than creating a new one.
====================
Posted by: Guest on April-03-2022

Code answers related to "Data Analytics with Pandas – How to Drop a List of Rows from a Pandas Dataframe"

Python Answers by Framework

Browse Popular Code Answers by Language