Change name to number with prefix

Question:

I have a problem. I would like to change the names into numbers, so that instead of the name there is a number. In addition, I would like the number to be preceded by a name, e.g. Max Power becomes Name 0.

When I use cat codes and then append a string, I get the following error

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U5'), dtype('int8')) -> None

How can I change the name to a number and put the name in front of it?

Dataframe

             name
0       Max Power
1  Erik Fullpower
2       Sofia Cat

Code

import pandas as pd
d = {'name': ['Max Power', 'Erik Fullpower', 'Sofia Cat']}
df = pd.DataFrame(data=d)


name = df['name'].astype('category').cat.codes
name = "Name " + name

What I want

             name
0       Name 0
1       Name 1
2       Name 2

Erorr

---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
<ipython-input-5-68feb913163d> in <module>
      1 name = df['name'].astype('category').cat.codes
----> 2 name = "Name " + name

5 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/roperator.py in radd(left, right)
      7 
      8 def radd(left, right):
----> 9     return right + left
     10 
     11 

UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U5'), dtype('int8')) -> None
Asked By: Test

||

Answers:

You mean like this>? or just name ?

import pandas as pd
d = {'name': ['Max Power', 'Erik Fullpower', 'Sofia Cat']}
df = pd.DataFrame(data=d)

df['name'] = df.assign(index=df.index.astype(str)).agg(' '.join, 1)
print(df)

output#

               name
0       Max Power 0
1  Erik Fullpower 1
2       Sofia Cat 2

or

More simpler

import pandas as pd

d = {'name': ['Max Power', 'Erik Fullpower', 'Sofia Cat']}
df = pd.DataFrame(data=d)
 

df['name'] =  df['name'] +' '+ df.index.astype(str)

print(df)

#output

               name
0       Max Power 0
1  Erik Fullpower 1
2       Sofia Cat 2

I’m so confused so Just adding another possible answer

import pandas as pd
d = {'name': ['Max Power', 'Erik Fullpower', 'Sofia Cat']}
df = pd.DataFrame(data=d)

df['name_'] = 'name'

df['name_'] =  df['name_'] +' '+ df.index.astype(str)

print(df)

output#

             name   name_
0       Max Power  name 0
1  Erik Fullpower  name 1
2       Sofia Cat  name 2
Answered By: Bhargav
df['name2'] = 'Name ' + (df['name'].astype('category').cat.codes).astype(str)
df
    name            name2
0   Max Power       Name 1
1   Erik Fullpower  Name 0
2   Sofia Cat       Name 2
Answered By: Naveed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.