简体   繁体   中英

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?

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']))

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'])

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