【问题标题】:concatenate multiindex into single index in pandas series将多索引连接成熊猫系列中的单个索引
【发布时间】:2018-03-05 20:11:06
【问题描述】:

我有一个带有多索引的pandas.Series

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

我想将多索引合并成单个索引,格式如下:

one_a   1.0
one_b   2.0
two_a   3.0
two_b   4.0
dtype: float64

有什么好的方法吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    mapjoin 一起使用:

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

    替代方案是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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2021-09-01
      • 2014-07-11
      • 1970-01-01
      • 2018-12-02
      • 2022-07-27
      相关资源
      最近更新 更多