3.1. Exercises

Column Editing Questions

Here is our fruit_salad dataframe once again.

           name    colour    location    seed   shape  sweetness   water-content  weight
0         apple       red     canada    True   round     True          84         100
1        banana    yellow     mexico   False    long     True          75         120
2    cantaloupe    orange      spain    True   round     True          90        1360
3  dragon-fruit   magenta      china    True   round    False          96         600
4    elderberry    purple    austria   False   round     True          80           5
5           fig    purple     turkey   False    oval    False          78          40
6         guava     green     mexico    True    oval     True          83         450
7   huckleberry      blue     canada    True   round     True          73           5
8          kiwi     brown      china    True   round     True          80          76
9         lemon    yellow     mexico   False    oval    False          83          65


Let’s say we run the following code:

fruit_salad.drop(columns = ['colour', 'shape', 'sweetness'])
fruit_salad = fruit_salad.rename(columns={'location':'country',
                                          'weight':'weight_g'})

Use the dataframe and code above to answer the next 2 questions.

Coding questions

Instructions:
Running a coding exercise for the first time, could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.


Renaming a Column Index

Let’s rename one of the columns in our pokemon.csv data.

Tasks:

  • Rename the column sp_attack to special_a and sp_defense to special_d using .rename() only once.
  • Save the new dataframe as pokemon_special.
  • Display the first 5 rows of the dataframe.
Hint 1
  • Are you using pokemon.rename()?
  • Are you saving the new dataframe as the correct name?
  • Are you using the argument columns={'sp_attack':'special_a', 'sp_defense':'special_d'}?
Fully worked solution:


Dropping Columns in a Dataframe

Some of the columns in pokemon.csv we have deemed not useful. Let’s get rid of them!

Tasks:

  • Drop the columns deck_no, capture_rt, and legendary.
  • Make sure to overwrite the new dataframe to object pokemon.
  • Display the first 5 rows of the dataframe.
Hint 1
  • Are you using pokemon.drop()?
  • Are you overwriting the new dataframe to object pokemon?
  • Are you using square brackets in the argument columns?
Fully worked solution: