Dropping Specific Rows from a Pandas Dataframe using a List of Indices
To remove rows from a Pandas dataframe based on specific indices, the DataFrame.drop function is commonly utilized. Let's delve into its usage:
Consider a dataframe df with data on sales, discount, net sales, and COGS:
<code class="python">>>> df 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</code>
Now, suppose we want to drop the rows with sequence numbers 1, 2, and 4:
<code class="python">list_of_indices = [1, 2, 4]</code>
To achieve this, we can apply the DataFrame.drop function along with a Series of indices:
<code class="python">df = df.drop(index=list_of_indices)</code>
As a result, the modified df will only contain the remaining rows:
<code class="python">>>> df 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</code>
This approach allows us to selectively remove rows from a dataframe based on a specified list of indices, making it a versatile tool for data manipulation in Pandas.
The above is the detailed content of How to Drop Specific Rows from a Pandas DataFrame Using a List of Indices?. For more information, please follow other related articles on the PHP Chinese website!