Pivot tables

A pivot table, as known from Excel, summarizes data. The data in CSV files that we have seen in this chapter so far has been in flat files. The pivot table aggregates data from a flat file for certain columns and rows. The aggregating operation can be sum, mean, standard deviations, and so on. We will reuse the data generating code from data_aggregation.py. The pandas API has a top-level pivot_table() function and corresponding DataFrame method. With the aggfunc parameter, we can specify the aggregation function to use the NumPy sum() function, for instance. The cols parameter tells pandas the column to be aggregated. Create a pivot table on the Food column as follows:

print pd.pivot_table(df, cols=['Food'], aggfunc=np.sum)

The pivot ...

Get Python Data Analysis now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.