【问题标题】:How do I convert '$ -' from a string to a float using pandas?如何使用 pandas 将 '$ -' 从字符串转换为浮点数?
【发布时间】:2022-01-07 17:02:23
【问题描述】:

我有一些财务信息已在 Excel 文档中保存了一段时间,我想在其上运行一些 Python 代码,但在将对象类型转换为浮点数时遇到了一些问题。问题似乎是'$ -'

这是数据加载时的样子:

import pandas as pd
dfData = {'Item': ['Product 1','Product 2','Product 3'],
        'Cost': [14.87,'-9.47','$ -']
       }
df = pd.DataFrame(dfData,columns=['Item','Cost'])
df
         Item   Cost
0   Product 1   14.87
1   Product 2   -9.47
2   Product 3   $ -

我试过了:

df['Cost'] = df['Cost'].str.replace('$','').str.replace(' ','').astype('float')

...以及其他类似的 str.replace 命令,但我不断收到以下错误:

ValueError: could not convert string to float: ''

这是我的第一个堆栈溢出帖子,所以请放轻松!我已经到处寻找解决方案,但由于某种原因找不到解决这个特定问题的解决方案。我也无法替换“-”,因为第 1 行表示负值。

【问题讨论】:

  • 而不是用空白替换为 0 并尝试使用正则表达式。它会减少冗长

标签: python pandas string


【解决方案1】:

你不需要链接str.replace,你可以使用replace

df['Cost'] = df['Cost'].replace({'\$': '', '-': '-0'}, regex=True).astype(float)
print(df)

# Output
        Item   Cost
0  Product 1  14.87
1  Product 2  -9.47
2  Product 3  -0.00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2018-08-23
    • 2017-11-29
    • 1970-01-01
    • 2018-02-15
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多