Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping rows in pandas with .index

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?

like image 482
sonic23 Avatar asked Jun 21 '18 17:06

sonic23


People also ask

How do I drop a row using ILOC?

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.

How do I drop a row from a series in pandas?

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.

How do I delete a row in pandas DataFrame?

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.

How do you drop 10 rows in pandas?

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.


1 Answers

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=0and retrieve their index(and then use like in the documentation)

like image 142
Joe Avatar answered Oct 05 '22 23:10

Joe