Reshaping with pd.DataFrame.melt
In the Reshaping with pd.DataFrame.stack and pd.DataFrame.unstack recipe, we discovered that you could convert a wide pd.DataFrame
into long form by setting the appropriate row and column index(es) before calling pd.DataFrame.stack
. pd.TheDataFrame.melt
function also lets you convert your pd.DataFrame
from wide to long, but can do so without having to set the row and column index values in an intermediate step, while also offering more control over what other columns may or may not be included as part of the wide to long conversion.
How to do it
Let’s once again create a summary of the different fruits being grown in different states. However, unlike the Reshaping with pd.DataFrame.stack and pd.DataFrame.unstack recipe, we will not be setting the row index to the state values, and instead, just treating it as another column in our pd.DataFrame
:
df = pd.DataFrame([
["Texas", 12, 10, 40],
["Arizona", 9,...