Tim Hopper
Tim Hopper

Reputation: 925

Appending a level to a Pandas Series Index

I'm trying to append a level to a Pandas Series. Say a create a simple Series:

 series = pd.Series(range(10), index = list("ABCDEFGHIJ"))

series has a single index level. I want to add a second level. With a DataFrame you can use DataFrame.set_index to do this somewhat cleanly. However, without converting my series to a DataFrame first, the easiest thing I've come up with is something such as:

 index =  [np.array(["L2" for x in series.index]), np.array(series.index)]     
 series2 = pd.Series(series.tolist(), index = index)

series2 now has a multiindex with two levels.

Is there any easier and cleaner approach to this?

Upvotes: 5

Views: 4717

Answers (2)

William de Vazelhes
William de Vazelhes

Reputation: 476

A simple way to do it (inplace) is:

series.index = pd.MultiIndex.from_product([['L2'], series.index])

EDIT there is also another way to do the same thing (not inplace):

series2 = pd.concat([series], keys=['L2'])

Upvotes: 5

miku
miku

Reputation: 188034

Not sure this is much cleaner; there's a MultiIndex class that can be used to construct hierarchical indices:

>>> import pandas as pd
>>> series = pd.Series(range(10), index = list("ABCDEFGHIJ"))

Create a new object, reusing the the original series index:

>>> pd.Series(xrange(10), 
              pd.MultiIndex.from_tuples([('L2', a) for a in series.index]))
L2  A    0
    B    1
    C    2
    D    3
    E    4
    F    5
    G    6
    H    7
    I    8
    J    9
dtype: int64

Or can alter a series in-place as well:

>>> import pandas as pd
>>> series = pd.Series(range(10), index = list("ABCDEFGHIJ"))
>>> series.index = pd.MultiIndex.from_tuples([('L2', a) for a in series.index])

Or just start with a MultiIndex altogether:

>>> import pandas as pd
>>> series = pd.Series(range(10), index=pd.MultiIndex.from_tuples(
                                        [('L2', x) for x in 'ABCDEFGHIJ']))

Upvotes: 4

Related Questions