价格列对象要转换为int

kwa*_*122 1 python pandas ipython-notebook

我有一个名为amount的列,其中包含如下所示的值:$ 3,092.44当我执行dataframe.dtypes()此操作时,该列将其作为对象返回,如何将该列转换为int类型?

小智 15

这就是你如何做到这一点,同时也放弃了美分:

car_sales["Price"] = car_sales["Price"].str.replace('[\$\,]|\.\d*', '').astype(int)
Run Code Online (Sandbox Code Playgroud)


piR*_*red 11

在正则表达式中\D意味着不是数字......所以我们可以使用pd.Series.str.replace

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

0    309244
1    309244
Name: amount, dtype: int64
Run Code Online (Sandbox Code Playgroud)


jez*_*ael 5

您可以使用Series.replaceSeries.str.replaceSeries.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
Run Code Online (Sandbox Code Playgroud)
dataframe['amount'] = dataframe['amount'].str.replace('[\$\,\.]', '').astype(int)

print (dataframe)
   amount
0  309244
1  309244
Run Code Online (Sandbox Code Playgroud)