首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >pandas列数据类型: object to int - Error: float‘对象没有属性'replace’

pandas列数据类型: object to int - Error: float‘对象没有属性'replace’
EN

Stack Overflow用户
提问于 2021-11-12 21:52:53
回答 1查看 52关注 0票数 1

pandas dataframe中的示例数据:

代码语言:javascript
运行
复制
df['Revenue']


0                $0.00
1       $12,982,681.00
2                  NaN
3       $10,150,623.00
4                  NaN
             ...      
1713               NaN
1714               NaN
1715               NaN
1716               NaN
1717               NaN
Name: Revenue, Length: 1718, dtype: object    

我需要将列从currency format更改为integer,以便可以运行计算和聚合。

代码语言:javascript
运行
复制
# Fix format currency
if df['Revenue'].dtype == 'object':

    df['Revenue'] = df['Revenue'].apply(lambda x: x.replace('$','')).apply(lambda x: x.replace(',','')).astype(np.int64)

当我运行上面的代码行来转换数据类型时,我遇到了以下错误:

代码语言:javascript
运行
复制
  3 # Fix format currency
  4 if df['Revenue'].dtype == 'object':
  5     df['Revenue'] = df['Revenue'].apply(lambda x: x.replace('$','')).apply(lambda x: x.replace(',','')).astype(np.int64)
 

  AttributeError: 'float' object has no attribute 'replace'
EN

回答 1

Stack Overflow用户

发布于 2021-11-12 21:57:23

您可以尝试替换除数字和点之外的所有内容。如果您以csv格式读取文件,则可以在读取阶段对其进行控制。

代码语言:javascript
运行
复制
 df['Revenue'].fillna(0).astype(str).replace('[^0-9\.]','', regex=True).str.split('\.').str[0].astype(int)



    Revenue
0            0
1     12982681
2            0
3     10150623
4            0
1713         0
1714         0
1715         0
1716         0
1717         0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69949454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档