I came across the below line of code, which gives an error when '.index' is not present in it.
print(df.drop(df[df['Quantity'] == 0].index).rename(columns={'Weight': 'Weight (oz.)'}))
What is the purpose of '.index' while using drop in pandas?
Use iloc to get the row as a Series, then get the row's index as the 'name' attribute of the Series. Then use the index to drop.
The pandas series. drop() method is used to remove a specific row from the pandas series object. And It will return a series object with the removed row. The drop() method can be applied to both labeled-based and position index abased series objects.
DataFrame. drop() method you can drop/remove/delete rows from DataFrame. axis param is used to specify what axis you would like to remove. By default axis = 0 meaning to remove rows.
Using iloc[] to Drop First N Rows of DataFrame Use DataFrame. iloc[] the indexing syntax [n:] with n as an integer to select the first n rows from pandas DataFrame. For example df. iloc[n:] , substitute n with the integer number specifying how many rows you wanted to delete.
As explained in the documentation, you can use drop
with index
:
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
df.drop([0, 1]) # Here 0 and 1 are the index of the rows
Output:
A B C D
2 8 9 10 11
In this case it will drop the first 2 rows.
With .index
in your example, you find the rows where Quantity=0
and retrieve their index(and then use like in the documentation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With