Tidying variable values as column names with melt
Like most large Python libraries, pandas has many different ways to accomplish the same task, the differences usually being readability and performance. A DataFrame has a method named .melt
that is similar to the .stack
method described in the previous recipe but gives a bit more flexibility.
In this recipe, we use the .melt
method to tidy a DataFrame with variable values as column names.
How to do it…
- Read in the
state_fruit2.csv
dataset:>>> state_fruit2 = pd.read_csv('data/state_fruit2.csv') >>> state_fruit2 State Apple Orange Banana 0 Texas 12 10 40 1 Arizona 9 7 12 2 Florida 0 14 190
- Use the
.melt
method by passing the appropriate columns to theid_vars
andvalue_vars
parameters:>>> state_fruit2.melt(id_vars=['State'], ... value_vars=['Apple', &apos...