Deleting and Inserting Rows in a DataFrame
Series object is like a NumPy array that has labels—access labels. These are called, as we know, the index. So for example, if I take a look at the last row, the index is going to be the columns of the DataFrame where we extracted the
Series object. In this case, it’s
py-score. Also notice that it’s got this
Name attribute, which in this case is
16, which corresponds to the row label in the original DataFrame.
This gives us a way to think about how we can add either rows or columns to a DataFrame. So, for example, let’s suppose we wanted to add a new row corresponding to a new job candidate. So, for example, let’s suppose this is going to be a job candidate named
john. Let’s create a
Series object, so we call the constructor
Series() from the
This is going to take a couple of keyword arguments. So,
data—this is going to be the actual data representing this new row, which is going to be we need a
age, and, of course, a
02:27 Now, we also want to give this series a index. And in this case, because we’re going to be creating a new row that we’re going to be adding to the DataFrame, we want the index… As we saw, when we pull out a row, we want the index to be the same as the column labels of the DataFrame.
And then we’re going to pass in a new name, and the name is going to be the row label that we want to associate with this new row that we’re going to be adding, which, in this case, we’re going to put as
17. All right, so that creates a new
Series object. Let’s go ahead and run that.
In this case, we’re appending a row, and this is going to be a
Series object, and we want to append the
Series object that we just created. Now, this is going to append this new row to the DataFrame, but it’s going to return a new DataFrame.
So if we go
.drop() and then we pass in what labels, what rows, we want to drop, we pass in a keyword argument for
labels, and this can be a list or it can be a single label. In this case, we’re going to drop the last row that we just added. And if we want, we’ll save this in the same name
df. And in this case, what’s happening is
.drop() is going to retain a new DataFrame, and so we can simply reassign the value of
df. So by default, the
.drop() method returns the pandas DataFrame with the specified rows removed.
In this case, we’re just removing one with label
17. But there’s also a keyword argument called
inplace, which actually exists for many of the methods in pandas. The default value is
False, and so if we were to pass a value of
True, then in this case, the original DataFrame will be modified by removing that row, and what you’ll get is your return value of
Become a Member to join the conversation.