将多索引连接成 pandas 系列中的单个索引 [英] concatenate multiindex into single index in pandas series
本文介绍了将多索引连接成 pandas 系列中的单个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有多索引的 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
:
Use map
with join
:
s.index = s.index.map('_'.join)
替代方法是列表推导
:
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
这篇关于将多索引连接成 pandas 系列中的单个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文