【发布时间】:2021-05-29 04:12:23
【问题描述】:
我写了一个函数,它的目的是将价格数据从美元转换为整数。很简单。
每个条目上的数据格式如下所示(通过示例):$40.00、$1,100.00 等
注意:值得一提的是,在我进行任何astype() 更改之前,dtype 最初是一个对象。
def convert_price(df):
df['price'] = df['price'].str.replace('$', '')
df['price'] = df['price'].str.replace(',', '') # these two lines remove unwanted symbols. Leaving me with a '1100.00' for example
df['price'] = df['price'].astype('Int64') # convert data to int.
return df
我收到一个错误:无法将对象转换为 IntegerDtype。
我尝试解决它,如之前在 SoF 问题中提到的那样,首先转换为浮点数,然后转换为整数:
def convert_price(df):
df['price'] = df['price'].str.replace('$', '')
df['price'] = df['price'].str.replace(',', '')
df['price'] = df['price'].astype('float')
df['price'] = df['price'].astype('Int64')
return df
新错误:无法安全地将非等效 float64 转换为 int64
然后我搜索了潜在的缺失值:
df[['price']].isna().sum()
output:
price 0
dtype: int64
没有找到,但尽管我得到了错误, 检查系列的 dtype 会返回“int64”。
谁能向我解释这里到底发生了什么。在调用我的函数来表达它时,我得到了错误,如上所述。但是输出似乎给出了我想要的结果?
编辑:小数据样本
【问题讨论】:
-
您是否也尝试过删除点(“.”)?
-
请添加您的约会样例
-
我做到了,是的。我的想法是删除“。”然后除以 100。但我收到一个错误。