Column renaming and column dropping

candy = pd.read_csv('data/candybars.csv')
candy
name weight chocolate peanuts caramel nougat cookie_wafer_rice coconut white_chocolate multi available_canada_america
0 Coffee Crisp 50 1 0 0 0 1 0 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 0 0 America
2 Skor 39 1 0 1 0 0 0 0 0 Both
... ... ... ... ... ... ... ... ... ... ... ...
22 Almond Joy 46 1 0 0 0 0 1 0 0 America
23 Oh Henry 51 1 1 1 0 0 0 0 0 Both
24 Cookies and Cream 43 0 0 0 0 1 0 1 0 Both

25 rows × 11 columns

Column Renaming

candy = candy.rename(columns={'available_canada_america':'availability'})
candy
name weight chocolate peanuts caramel nougat cookie_wafer_rice coconut white_chocolate multi availability
0 Coffee Crisp 50 1 0 0 0 1 0 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 0 0 America
2 Skor 39 1 0 1 0 0 0 0 0 Both
... ... ... ... ... ... ... ... ... ... ... ...
22 Almond Joy 46 1 0 0 0 0 1 0 0 America
23 Oh Henry 51 1 1 1 0 0 0 0 0 Both
24 Cookies and Cream 43 0 0 0 0 1 0 1 0 Both

25 rows × 11 columns


 columns={'old column name':'new column name'}
candy = candy.rename(columns={'available_canada_america':'availability',
                        'weight':'weight_g'})
candy.head()
name weight_g chocolate peanuts caramel nougat cookie_wafer_rice coconut white_chocolate multi availability
0 Coffee Crisp 50 1 0 0 0 1 0 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 0 0 America
2 Skor 39 1 0 1 0 0 0 0 0 Both
3 Smarties 45 1 0 0 0 0 0 0 1 Canada
4 Twix 58 1 0 1 0 1 0 0 1 Both

Column Dropping

candy.drop(columns='coconut')
name weight_g chocolate peanuts caramel nougat cookie_wafer_rice white_chocolate multi availability
0 Coffee Crisp 50 1 0 0 0 1 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 0 America
2 Skor 39 1 0 1 0 0 0 0 Both
... ... ... ... ... ... ... ... ... ... ...
22 Almond Joy 46 1 0 0 0 0 0 0 America
23 Oh Henry 51 1 1 1 0 0 0 0 Both
24 Cookies and Cream 43 0 0 0 0 1 1 0 Both

25 rows × 10 columns

candy.drop(columns='coconut')


candy.head()
name weight_g chocolate peanuts caramel nougat cookie_wafer_rice coconut white_chocolate multi availability
0 Coffee Crisp 50 1 0 0 0 1 0 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 0 0 America
2 Skor 39 1 0 1 0 0 0 0 0 Both
3 Smarties 45 1 0 0 0 0 0 0 1 Canada
4 Twix 58 1 0 1 0 1 0 0 1 Both


candy = candy.drop(columns=['nougat', 'coconut'])
candy.head()
name weight_g chocolate peanuts caramel cookie_wafer_rice white_chocolate multi availability
0 Coffee Crisp 50 1 0 0 1 0 0 Canada
1 Butterfinger 184 1 1 1 0 0 0 America
2 Skor 39 1 0 1 0 0 0 Both
3 Smarties 45 1 0 0 0 0 1 Canada
4 Twix 58 1 0 1 1 0 1 Both

Let’s apply what we learned!