Search code examples
pythonpandaspivotseries

Pivoting a Series in Pandas


I have a series that looks like this:

Area        Classification         Samples
88          500m-1bi               34
94          500m-1bi               112
09          500m-1bi               912
            >1bi                   31
81          <1m                    6574
87          100-500m               12
...

I want that the 'Classification' labels become columns and that 'Samples' become the values, so it looks like this:

Area       <1m    100-500m     500-1bi      >1bi  
88                             34
94                             112
09                             912          31
81         6574
87                12
...

I've tried:

df.pivot(columns='Classification', values='Samples')

But when I do that, I get AttributeError: 'Series' object has no attribute 'pivot'.

So I tried to turn it into a Dataframe:

df.to_frame().pivot(columns='Classification', values='Samples')

In this case I get:

KeyError: 'Classification'

Any idea on how to solve it?

** EDIT **

This series was obtained from a groupby function:

df=df.groupby(['Area','Classification']).agg('count').sort_values('Samples')['Samples']

Solution

  • A slightly modified df for this example. Added the 10 in Area to fill in the gap:

    Area        Classification         Samples
    88          500m-1bi               34
    94          500m-1bi               112
    09          500m-1bi               912
    10          >1bi                   31
    81          <1m                    6574
    87          100-500m               12
    

    You need to set the index then unstack:

    df.set_index(['Area', 'Classification']).unstack()
    

    Output:

                    Samples                       
    Classification 100-500m 500m-1bi     <1m  >1bi
    Area                                          
    9                   NaN    912.0     NaN   NaN
    10                  NaN      NaN     NaN  31.0
    81                  NaN      NaN  6574.0   NaN
    87                 12.0      NaN     NaN   NaN
    88                  NaN     34.0     NaN   NaN
    94                  NaN    112.0     NaN   NaN