How to do it...

  1. Read in the state_fruit2 dataset and identify which columns need to be transformed and which ones do not:
>>> state_fruit2 = pd.read_csv('data/state_fruit2.csv')
>>> state_fruit2
  1. Use the melt method by passing the appropriate columns to the id_vars and value_vars parameters:
>>> state_fruit2.melt(id_vars=['State'],
value_vars=['Apple', 'Orange', 'Banana'])
  1. This one step creates tidy data for us. By default, melt refers to the transformed former column names as variable and the corresponding values as value. Conveniently, melt has two additional parameters, var_name and value_name, that give you the ability to rename these two columns:
>>> state_fruit2.melt(id_vars=['State'],
value_vars=['Apple', 'Orange', 'Banana'],
var_name='Fruit',
value_name='Weight')
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset