简体   繁体   中英

concatenate multiindex into single index in pandas series

I have a pandas.Series with multiindex:

index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
                                   ('two', 'a'), ('two', 'b')])
s = pd.Series(np.arange(1.0, 5.0), index=index)
print(s)
one  a   1.0
     b   2.0
two  a   3.0
     b   4.0
dtype: float64

I want to merge the multiindex into a single index in the following form:

one_a   1.0
one_b   2.0
two_a   3.0
two_b   4.0
dtype: float64

Is there a nice way to do this?

Use map with join :

s.index = s.index.map('_'.join)

Alternative is list comprehension :

s.index = ['{}_{}'.format(i, j) for i, j in s.index]

print (s)
one_a    1.0
one_b    2.0
two_a    3.0
two_b    4.0
dtype: float64

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