获取数据中的熊猫系列索引

用户名

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

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,而不是迭代的序列。

海盗

选项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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章