There's more...

One of the keys to using stack is to place all of the columns that you do not wish to transform in the index. The dataset in this recipe was initially read with the states in the index. Let's take a look at what would have happened if we did not read the states into the index:

>>> state_fruit2 = pd.read_csv('data/state_fruit2.csv')
>>> state_fruit2

As the state names are not in the index, using stack on this DataFrame reshapes all values into one long Series of values:

>>> state_fruit2.stack()
0 State Texas
Apple 12 Orange 10 Banana 40 1 State Arizona Apple 9 Orange 7 Banana 12 2 State Florida Apple 0 Orange 14 Banana 190 dtype: object

This command reshapes all the columns, this time including the states, and is not at all what we need. In order to reshape this data correctly, you will need to put all the non-reshaped columns into the index first with the set_index method, and then use stack. The following code gives a similar result to step 1:

>>> state_fruit2.set_index('State').stack()
..................Content has been hidden....................

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