3

I want to format a series of strings so the index is in the string somewhere. Example series:

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

The desired output:

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

I've tried variants of this:

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

but it doesn't work because x.index refers to the index method of str, not the series being iterated over.

user1717828
  • 7,122
  • 8
  • 34
  • 59

1 Answers1

5

Option 1
pd.Index.to_series

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

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

Option 2 My favorite!
pd.Series.radd

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

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

Option 3

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

Jessica    Jessica: CT
Eric          Eric: NY
Toby          Toby: MT
dtype: object
piRSquared
  • 285,575
  • 57
  • 475
  • 624