【问题标题】:Get pandas series index in data获取数据中的熊猫系列索引
【发布时间】:2017-12-23 18:34:37
【问题描述】:

我想格式化一系列字符串,以便索引位于字符串中的某个位置。示例系列:

ser = pd.Series(['CT', 'NY', 'MT'], index=['Jessica', 'Eric', 'Toby'])
ser
Jessica    CT
Eric       NY
Toby       MT
dtype: object

想要的输出:

Jessica    Jessica: CT
Eric          Eric: NY
Toby          Toby: MT
dtype: object

我已经尝试过这种变体:

ser.apply(lambda x: "{}: {}".format(x.index, x))

但它不起作用,因为x.index 指的是str 的索引方法,而不是被迭代的系列。

【问题讨论】:

标签: python pandas indexing series


【解决方案1】:

选项 1
pd.Index.to_series

ser.index.to_series() + ': ' + ser

Jessica    Jessica: CT
Eric          Eric: NY
Toby          Toby: MT
dtype: object

选项 2 我最喜欢的!
pd.Series.radd

ser.radd(ser.index + ': ')

Jessica    Jessica: CT
Eric          Eric: NY
Toby          Toby: MT
dtype: object

选项 3

pd.Series(map(': '.join, zip(ser.index, ser)), ser.index)

Jessica    Jessica: CT
Eric          Eric: NY
Toby          Toby: MT
dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 2014-10-11
    • 2023-02-10
    • 2016-04-19
    • 2016-02-06
    相关资源
    最近更新 更多