Convert str(Object) to int (python)

Asked

Viewed 5,443 times

0

I have a dataset with two columns and would like to create a third column called Ranking that will receive values based on the Brand column. So Mark A will receive the value 10 and so on.

df = {'Marca' : ['A', 'B', 'C'],
 'Valores': ['10', '11', '12']}

df['Ranking'] = df['Marca'].apply(lambda x: x.replace('A','10')
                                          .replace('B', '11')
                                          .replace('C', '12'))

With this function the code worked, however the Ranking column dtype is like Object, then I tried to use df.Ranking.astype(int)to transform into whole, but when I give a df.dtypescontinues as Object. Is there another way for me to treat this?? This column needs to be numerical as I will use it for modeling later. Note: the variable df is a Pandas object. Thank you.

  • 1

    Hello @Edi, you could edit your question and add in the tags the library you are using?

1 answer

1

To change the data type you need to assign the function result astype(int) back to the spine Ranking.

Using the data from your example

import Pandas as pd

df = pd.DataFrame({'Marca' : ['A', 'B', 'C'], 'Valores': ['10', '11', '12']})
df['Ranking'] = pdf['Marca'].apply(lambda x: x.replace('A', '10').replace('B', '11').replace('C', '12'))

If you check what kind of data you will get, as you indicated in your question, that df['Ranking'] has kind object

>>> df.dtypes
Marca      object
Valores    object
Ranking    object
dtype: object

Calling the astype() function and assigning the result back to the column df['Ranking']

df['Ranking'] = df['Ranking'].astype(int)

Going back to check the type of data, you will get:

>>> df.dtypes
Marca      object
Valores    object
Ranking     int32
dtype: object
  • 1

    Thanks. It worked this way. Another one I learned. Thanks.

  • with me it doesn’t work

Browser other questions tagged

You are not signed in. Login or sign up in order to post.