Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Working with Excel Files
Summary

Instruction

Good job! We can also delete the rows or columns by using the delete_rows and delete_columns methods. Suppose we have a small worksheet, like the one you saw in the previous part:

id name position salary
1 John Doe Junior Developer 4000
2 Mary Sue Marketing Specialist 3500
3 Kate May Project Manager 5000
4 Janet Rainwood Developer 7000
5 Anne Bonnie Technical Writer 4200

The index of the row with the column names is 0. If we wanted to delete the row that contains all the data about Mary Sue, we would write:

ws.delete_rows(2)

where 2 signifies the row index. We could also add a second argument that would indicate the number of rows we want to delete, including the row given as the first argument. Here's an example:

ws.delete_rows(2, 3)

This removes three consecutive rows starting with the second one. We can do the same thing with columns. However, you must pass that column's index number, not the column's letter:

ws.delete_cols(3)

The code above deletes the column with the index 3 ("C"); in this case, that's information about the position of each employee.

Exercise

Bananas have been added to the Food worksheet four times instead of two. Delete the last two rows (11 and 12) from the worksheet.

Save the modified workbook in the file budget.xlsx.