简体   繁体   中英

Unstack and reorder pandas dataframe

I've searched around but couldn't find a solution for how to unstack and reorder a pandas dataframe.

Suppose I have the following dataframe:

df = pd.DataFrame({'type': [1, 2, 2, 1, 2, 1, 2, 1, 2, 2],
                   'band': ['A', 'B', 'C', 'C', 'B', 'B', 'A', 'A', 'B', 'C'],
                   'val': [0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27]})

I can group by 'type' and 'band' to get the mean across both dimensions, and use unstack() to show 'band' as columns:

df.groupby(['type', 'band']).mean().unstack(level=1)

My question is, how can I reorder the columns so that they're in descending (or more generally, any arbitrarily sorted) order?

The output looks like this:

    val
band    A   B           C
type            
1   0.215   0.230000    0.210
2   0.240   0.223333    0.235

What I want is the following:

    val
band    C   B           A
type            
1   0.210   0.230000    0.215
2   0.235   0.223333    0.240

In practice, I have many more than 3 columns.

It seems like you want sort_index on the columns:

df.groupby(['type', 'band']).mean().unstack(level=1)\
    .sort_index(axis=1, ascending=False)

Result:

        val              
band      C      B      A
type                     
1     0.210  0.230  0.215
2     0.235  0.223  0.240

As for an arbitrary order: say your order is "C, A, B". Generally, you must just specify this directly.

order = list('CAB')
df[order]

The output of df.groupby(['type', 'band']).mean().unstack(level=1) is another DataFrame. You can do the following:

df = df.groupby(['type', 'band']).mean().unstack(level=1)
df = df.reindex_axis(sorted(df.columns, reverse=True), axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM