Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate multiindex into single index in pandas series

Tags:

python

pandas

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?

like image 495
Jean Paul Avatar asked Mar 05 '18 12:03

Jean Paul


People also ask

How do I convert MultiIndex to single index in pandas?

To revert the index of the dataframe from multi-index to a single index using the Pandas inbuilt function reset_index(). Returns: (Data Frame or None) DataFrame with the new index or None if inplace=True.

Can you index a series in pandas?

Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.


1 Answers

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
like image 115
jezrael Avatar answered Oct 14 '22 16:10

jezrael