Get index of pandas series in data

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

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

      

Desired output:

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

      

I've tried variations of this:

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

      

but that doesn't work because it x.index

refers to the index method str

and not the series being iterated over.

+3


source to share


1 answer


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

      

+4


source







All Articles