Book Image

Pandas 1.x Cookbook - Second Edition

By : Matt Harrison, Theodore Petrou
Book Image

Pandas 1.x Cookbook - Second Edition

By: Matt Harrison, Theodore Petrou

Overview of this book

The pandas library is massive, and it's common for frequent users to be unaware of many of its more impressive features. The official pandas documentation, while thorough, does not contain many useful examples of how to piece together multiple commands as one would do during an actual analysis. This book guides you, as if you were looking over the shoulder of an expert, through situations that you are highly likely to encounter. This new updated and revised edition provides you with unique, idiomatic, and fun recipes for both fundamental and advanced data manipulation tasks with pandas. Some recipes focus on achieving a deeper understanding of basic principles, or comparing and contrasting two similar operations. Other recipes will dive deep into a particular dataset, uncovering new and unexpected insights along the way. Many advanced recipes combine several different features across the pandas library to generate results.
Table of Contents (17 chapters)
15
Other Books You May Enjoy
16
Index

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…

  1. 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
    
  2. 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', &apos...