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?
Pandas Series: append() functionThe append() function is used to concatenate two or more Series. Series to append with self. If True, do not use the index labels. If True, raise Exception on creating index with duplicates.
Step1: Define a Pandas series, s1. Step 2: Define another series, s2. Step 3: Append s2 to s1. Step 4: Print the final appended series.
rename() function in the pandas Series functionalities, which is used to change the series index labels or to change the name of the series object.
A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method. DataFrame. reset_index() is used to reset the index to default and make the index a column of the dataframe.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With