Deleting and Inserting Columns in a DataFrame
We need to pass in the location of the column where we want to add it at. So again, this is all zero-based index, so column
2, and so on. Let’s suppose we wanted to add this at position
4, so we’ll pass in a value of
4 for the
loc keyword argument.
Let’s suppose we wanted to delete that
total-score column. We’re going to be using similar notation as you would with a Python dictionary, so we can use
del (delete), and then the name of the column—in this case,
Another way to do this is to use the
.pop() method. The
.pop() method will delete the column that you want. and it will also return it, very similar to how you would with a list or a dictionary.
and then let’s delete it. This time, we’ll delete it with the
.pop() method, and this will be
'total-score'. And then, so you can see what this will return, let’s just save this with, say, the name
Let’s take a look at our current version of the DataFrame, which has
total-score column removed. Now, if you wanted to remove more than one column, you can use the
.drop() method just like we did with the rows, but in this case, you would have to pass a keyword argument of
.drop(), we can pass in… If we want it to remove the
'age' column. By default, this is going to be looking for the row with label
'age', and of course, our DataFrame doesn’t have such a row.
Instead, we want to tell pandas that this is a column, and so we’re removing a Series that’s in as a column, so we pass in a value of
1. The default value is
0, which means that it’s going to be removing a row. In this case, we want to remove a column, so we just pass in
axis=1. And again, we can either use
inplace or if we don’t, this will return a new DataFrame.
Maybe we’ll call this
df, and then we’ll view that value of
df after we do that operation. And so now we’ve removed the
age column. Again, if you wanted to remove more than one, you would just pass these on as a list, and so on. All right!
Become a Member to join the conversation.