【问题标题】:Pandas how to convert an array of strings ($0.00 format) into decimalsPandas 如何将字符串数组($0.00 格式)转换为小数
【发布时间】:2020-06-28 22:19:47
【问题描述】:

我正在尝试将代码中当前为字符串 $ 格式的列转换为数字。

我的代码目前是:

s=top_performing_schools["Per Student Budget"]

top_performing_schools["Per Student Budget"]=pd.to_numeric(s)

我得到错误:

ValueError: Unable to parse string "$582.00" at position 0

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以删除$ 符号,然后应用数字转换,例如:

import pandas as pd


df = pd.DataFrame(
    {"Per Student Budget": ["$582.00", "$100", "$12000"]}
)

df["Per Student Budget"] = pd.to_numeric(df["Per Student Budget"].str.replace('$', ''))
print(df)

   Per Student Budget
0               582.0
1               100.0
2             12000.0

【讨论】:

    【解决方案2】:

    将熊猫导入为 pd

    df = pd.DataFrame( {“每个学生的预算”:[“$582.00”,“$100”,“$12000”]} )

    df["每名学生预算"] = pd.to_numeric(df["每名学生预算"].str.replace('$', '')) 打印(df)

    每个学生的预算 0 582.0 1 100.0 2 12000.0

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2019-06-14
    • 2013-08-14
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多