Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Price column object to int in pandas

I have a column called amount with holds values that look like this: $3,092.44 when I do dataframe.dtypes() it returns this column as an object how can i convert this column to type int?

like image 779
kwashington122 Avatar asked Nov 28 '22 02:11

kwashington122


2 Answers

You can use Series.replace or Series.str.replace with Series.astype:

dataframe = pd.DataFrame(data={'amount':['$3,092.44', '$3,092.44']})
print (dataframe)
      amount
0  $3,092.44
1  $3,092.44

dataframe['amount'] = dataframe['amount'].replace('[\$\,\.]', '', regex=True).astype(int)

print (dataframe)
   amount
0  309244
1  309244

dataframe['amount'] = dataframe['amount'].astype(int)

print (dataframe)
   amount
0  309244
1  309244
like image 172
jezrael Avatar answered Dec 12 '22 09:12

jezrael


in regex \D means not digit... so we can use pd.Series.str.replace

dataframe.amount.replace('\D', '', regex=True).astype(int)

0    309244
1    309244
Name: amount, dtype: int64
like image 25
piRSquared Avatar answered Dec 12 '22 07:12

piRSquared