Home > Article > Backend Development > How to Drop Specific Rows from a Pandas Dataframe?
Dropping Specific Rows from a Pandas Dataframe
When working with a Pandas dataframe, it often becomes necessary to remove certain rows based on specific criteria. One common requirement is to drop rows that correspond to a list of sequential numbers. This article tackles this problem and presents a comprehensive solution.
In the example provided, we have a dataframe called 'df' with the following data:
sales discount net_sales cogs STK_ID RPT_Date 600141 20060331 2.709 NaN 2.709 2.245 20060630 6.590 NaN 6.590 5.291 20060930 10.103 NaN 10.103 7.981 20061231 15.915 NaN 15.915 12.686 20070331 3.196 NaN 3.196 2.710 20070630 7.907 NaN 7.907 6.459
Suppose we want to drop rows 1, 2, and 4 from this dataframe. To achieve this, we can utilize the 'DataFrame.drop' method. This method takes a 'Series' object as an argument, which contains the index labels of the rows we want to remove.
The following code snippet illustrates how to drop rows 1, 2, and 4 from our dataframe:
drop_list = [1, 2, 4] df.drop(index=drop_list, inplace=True)
Here, we create a list called 'drop_list' containing the index labels of the rows to be dropped. We then pass this list to the 'DataFrame.drop' method, specifying the 'index' parameter to indicate that we want to drop rows. Finally, the 'inplace=True' argument ensures that the dataframe is modified in place, without the need to assign it to a new variable.
After executing the above code, our dataframe will be updated as follows:
sales discount net_sales cogs STK_ID RPT_Date 600141 20060331 2.709 NaN 2.709 2.245 20061231 15.915 NaN 15.915 12.686 20070630 7.907 NaN 7.907 6.459
As you can see, rows 1, 2, and 4 have been successfully removed from the dataframe. This method is highly effective for dropping specific rows based on index labels or other criteria and can be easily customized to meet your specific data manipulation requirements.
The above is the detailed content of How to Drop Specific Rows from a Pandas Dataframe?. For more information, please follow other related articles on the PHP Chinese website!