Skip to content
Advertisement

How can I pivot a dataframe?

  • What is pivot?
  • How do I pivot?
  • Long format to wide format?

I’ve seen a lot of questions that ask about pivot tables, even if they don’t know it. It is virtually impossible to write a canonical question and answer that encompasses all aspects of pivoting… But I’m going to give it a go.


The problem with existing questions and answers is that often the question is focused on a nuance that the OP has trouble generalizing in order to use a number of the existing good answers. However, none of the answers attempt to give a comprehensive explanation (because it’s a daunting task). Look at a few examples from my Google search:

  1. How to pivot a dataframe in Pandas? – Good question and answer. But the answer only answers the specific question with little explanation.
  2. pandas pivot table to data frame – OP is concerned with the output of the pivot, namely how the columns look. OP wanted it to look like R. This isn’t very helpful for pandas users.
  3. pandas pivoting a dataframe, duplicate rows – Another decent question but the answer focuses on one method, namely pd.DataFrame.pivot

Setup

I conspicuously named my columns and relevant column values to correspond with how I’m going to pivot in the answers below.

JavaScript
JavaScript

Questions

  1. Why do I get ValueError: Index contains duplicate entries, cannot reshape?

  2. How do I pivot df such that the col values are columns, row values are the index, and mean of val0 are the values?

    JavaScript
  3. How do I make it so that missing values are 0?

    JavaScript
  4. Can I get something other than mean, like maybe sum?

    JavaScript
  5. Can I do more that one aggregation at a time?

    JavaScript
  6. Can I aggregate over multiple value columns?

    JavaScript
  7. Can I subdivide by multiple columns?

    JavaScript
  8. Or

    JavaScript
  9. Can I aggregate the frequency in which the column and rows occur together, aka “cross tabulation”?

    JavaScript
  10. How do I convert a DataFrame from long to wide by pivoting on ONLY two columns? Given,

    JavaScript

    The expected should look something like

    JavaScript
  11. How do I flatten the multiple index to single index after pivot?

    From

    JavaScript

    To

    JavaScript

Advertisement

Answer

Here is a list of idioms we can use to pivot

  1. pd.DataFrame.pivot_table

    • A glorified version of groupby with more intuitive API. For many people, this is the preferred approach. And it is the intended approach by the developers.
    • Specify row level, column levels, values to be aggregated, and function(s) to perform aggregations.
  2. pd.DataFrame.groupby + pd.DataFrame.unstack

    • Good general approach for doing just about any type of pivot
    • You specify all columns that will constitute the pivoted row levels and column levels in one group by. You follow that by selecting the remaining columns you want to aggregate and the function(s) you want to perform the aggregation. Finally, you unstack the levels that you want to be in the column index.
  3. pd.DataFrame.set_index + pd.DataFrame.unstack

    • Convenient and intuitive for some (myself included). Cannot handle duplicate grouped keys.
    • Similar to the groupby paradigm, we specify all columns that will eventually be either row or column levels and set those to be the index. We then unstack the levels we want in the columns. If either the remaining index levels or column levels are not unique, this method will fail.
  4. pd.DataFrame.pivot

    • Very similar to set_index in that it shares the duplicate key limitation. The API is very limited as well. It only takes scalar values for index, columns, values.
    • Similar to the pivot_table method in that we select rows, columns, and values on which to pivot. However, we cannot aggregate and if either rows or columns are not unique, this method will fail.
  5. pd.crosstab

    • This a specialized version of pivot_table and in its purest form is the most intuitive way to perform several tasks.
  6. pd.factorize + np.bincount

    • This is a highly advanced technique that is very obscure but is very fast. It cannot be used in all circumstances, but when it can be used and you are comfortable using it, you will reap the performance rewards.
  7. pd.get_dummies + pd.DataFrame.dot

    • I use this for cleverly performing cross tabulation.

See also:


Question 1

Why do I get ValueError: Index contains duplicate entries, cannot reshape

This occurs because pandas is attempting to reindex either a columns or index object with duplicate entries. There are varying methods to use that can perform a pivot. Some of them are not well suited to when there are duplicates of the keys on which it is being asked to pivot. For example: Consider pd.DataFrame.pivot. I know there are duplicate entries that share the row and col values:

JavaScript

So when I pivot using

JavaScript

I get the error mentioned above. In fact, I get the same error when I try to perform the same task with:

JavaScript

Examples

What I’m going to do for each subsequent question is to answer it using pd.DataFrame.pivot_table. Then I’ll provide alternatives to perform the same task.

Questions 2 and 3

How do I pivot df such that the col values are columns, row values are the index, and mean of val0 are the values?

  • pd.DataFrame.pivot_table

    JavaScript
    • aggfunc='mean' is the default and I didn’t have to set it. I included it to be explicit.

How do I make it so that missing values are 0?

  • pd.DataFrame.pivot_table

    • fill_value is not set by default. I tend to set it appropriately. In this case I set it to 0.
    JavaScript
  • pd.DataFrame.groupby

    JavaScript
  • pd.crosstab

    JavaScript

Question 4

Can I get something other than mean, like maybe sum?

  • pd.DataFrame.pivot_table

    JavaScript
  • pd.DataFrame.groupby

    JavaScript
  • pd.crosstab

    JavaScript

Question 5

Can I do more that one aggregation at a time?

Notice that for pivot_table and crosstab I needed to pass list of callables. On the other hand, groupby.agg is able to take strings for a limited number of special functions. groupby.agg would also have taken the same callables we passed to the others, but it is often more efficient to leverage the string function names as there are efficiencies to be gained.

  • pd.DataFrame.pivot_table

    JavaScript
  • pd.DataFrame.groupby

    JavaScript
  • pd.crosstab

    JavaScript

Question 6

Can I aggregate over multiple value columns?

  • pd.DataFrame.pivot_table we pass values=['val0', 'val1'] but we could’ve left that off completely

    JavaScript
  • pd.DataFrame.groupby

    JavaScript

Question 7

Can I subdivide by multiple columns?

  • pd.DataFrame.pivot_table

    JavaScript
  • pd.DataFrame.groupby

    JavaScript

Question 8

Can I subdivide by multiple columns?

  • pd.DataFrame.pivot_table

    JavaScript
  • pd.DataFrame.groupby

    JavaScript
  • pd.DataFrame.set_index because the set of keys are unique for both rows and columns

    JavaScript

Question 9

Can I aggregate the frequency in which the column and rows occur together, aka “cross tabulation”?

  • pd.DataFrame.pivot_table

    JavaScript
  • pd.DataFrame.groupby

    JavaScript
  • pd.crosstab

    JavaScript
  • pd.factorize + np.bincount

    JavaScript
  • pd.get_dummies

    JavaScript

Question 10

How do I convert a DataFrame from long to wide by pivoting on ONLY two columns?

  • DataFrame.pivot

    The first step is to assign a number to each row – this number will be the row index of that value in the pivoted result. This is done using GroupBy.cumcount:

    JavaScript

    The second step is to use the newly created column as the index to call DataFrame.pivot.

    JavaScript
  • DataFrame.pivot_table

    Whereas DataFrame.pivot only accepts columns, DataFrame.pivot_table also accepts arrays, so the GroupBy.cumcount can be passed directly as the index without creating an explicit column.

    JavaScript

Question 11

How do I flatten the multiple index to single index after pivot

If columns type object with string join

JavaScript

else format

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement