Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object to Int pandas

Hello I have an issue to convert column of object to integer for complete column.

I have a data frame and I tried to convert some columns that are detected as Object into Integer (or Float) but all the answers I already found are working for me

First status

Then I tried to apply the to_numeric method but doesn't work. To numeric method

Then a custom method that you can find here: Pandas: convert dtype 'object' to int but doesn't work either: data3['Title'].astype(str).astype(int) ( I cannot pass the image anymore - You have to trust me that it doesn't work)

I tried to use the inplace statement but doesn't seem to be integrated in those methods:

I am pretty sure that the answer is dumb but cannot find it

like image 972
Pitchkrak Avatar asked Dec 05 '22 14:12

Pitchkrak


2 Answers

You need assign output back:

#maybe also works omit astype(str)
data3['Title'] = data3['Title'].astype(str).astype(int)

Or:

data3['Title'] = pd.to_numeric(data3['Title'])

Sample:

data3 = pd.DataFrame({'Title':['15','12','10']})
print (data3)
  Title
0    15
1    12
2    10

print (data3.dtypes)
Title    object
dtype: object

data3['Title'] = pd.to_numeric(data3['Title'])
print (data3.dtypes)
Title    int64
dtype: object

data3['Title'] = data3['Title'].astype(int)

print (data3.dtypes)
Title    int32
dtype: object
like image 164
jezrael Avatar answered Dec 24 '22 08:12

jezrael


As python_enthusiast said ,

This command works for me too

data3.Title = data3.Title.str.replace(',', '').astype(float).astype(int)

but also works fine with

data3.Title = data3.Title.str.replace(',', '').astype(int)

you have to use str before replace in order to get rid of commas only then change it to int/float other wise you will get error .

like image 42
dt170 Avatar answered Dec 24 '22 08:12

dt170