Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New index level name after DataFrame.stack()

Tags:

python

pandas

(Note that this SO question is similar-looking but different.)

I have a MultiIndexed DataFrame with columns representing yearly data:

>>> x = pd.DataFrame({
 'country': {0: 4.0, 1: 8.0, 2: 12.0},
 'series': {0: 553.0, 1: 553.0, 2: 553.0},
'2000': {0: '1100', 1: '28', 2: '120'},
 '2005': {0: '730', 1: '24', 2: '100'}
}).set_index(['country', 'series'])
>>> x
                2000 2005
country series           
4       553     1100  730
8       553       28   24
12      553      120  100

When I stack the years, the new index level has no name:

>>> x.stack()
country  series      
4        553     2000    1100
                 2005     730
8        553     2000      28
                 2005      24
12       553     2000     120
                 2005     100
dtype: object

Is there a nice way to tell stack I'd like the new level to be called 'year'? It doesn't mention this in the docs.

I can always do:

>>> x.columns.name = 'year'
>>> x.stack()

But, to my mind, this doesn't qualify as very 'nice'. Can anyone do it in one line?

like image 870
LondonRob Avatar asked Feb 03 '15 16:02

LondonRob


1 Answers

There is a chaining-friendly way to do it in one line (although admittedly not much nicer) using DataFrame.rename_axis:

x.rename_axis('year', axis=1).stack()
like image 82
mcwitt Avatar answered Oct 10 '22 13:10

mcwitt