Reputation: 5508
I have the following series:
ser = pd.Series(["foo","bar","a",4,5], index=["a", "b", "c", "d", "e"])
ser
a foo
b bar
c a
d 4
e 5
dtype: object
I want to concatenate an incrementing string number before the index as follows:
#desired output
0_a foo
1_b bar
2_c a
3_d 4
4_e 5
dtype: object
I tried this:
increment = iter(range(0,10))
ser.index = str(next(increment))+"_"+ser.index
but the string number doesn't increment. How should I approach this?
Upvotes: 1
Views: 97
Reputation: 863341
Use list comprehension with f-string
s and enumerate
:
ser.index = [f'{a}_{b}' for a, b in enumerate(ser.index)]
Or join RangeIndex
converted to strings with str.cat
:
ser.index = pd.RangeIndex(len(ser)).astype(str).str.cat(ser.index, sep='_')
Or:
ser.index = pd.RangeIndex(len(ser)).astype(str) + '_' + ser.index
print (ser)
0_a foo
1_b bar
2_c a
3_d 4
4_e 5
dtype: object
Upvotes: 1