【问题标题】:how to convert object data type into float in python data frame如何在python数据框中将对象数据类型转换为浮点数
【发布时间】:2019-01-11 15:29:31
【问题描述】:

enter image description here

-这是我的数据集包含特殊字符,所以我的问题是如何从数量列中删除该 A^ 符号.. - 从数据中删除该特殊符号后,我如何将此列转换为浮点类型..?

【问题讨论】:

    标签: python python-3.x python-2.7 dataframe data-science


    【解决方案1】:

    方法一

    您可以使用replaceto_numeric

    df['Quantity'] = pd.to_numeric(df.Quantity.str.replace('Â',''))
    

    示例

    >>> df
      Quantity  data
    0    0.1 Â     1
    1    0.2 Â     2
    
    df['Quantity'] = pd.to_numeric(df.Quantity.str.replace('Â',''))
    
    >>> df
       Quantity  data
    0       0.1     1
    1       0.2     2
    

    方法二

    另外,由于您的 Â 前面总是有一个空格,您可以使用 split 并取第一项:

    df['Quantity'] = pd.to_numeric(df['Quantity'].str.split().str[0])
    

    【讨论】:

    • 无法解析位置 0 处的字符串“0.1”
    • 有趣的是,我没有得到那个错误。但请尝试使用 strip 去除尾随空格:pd.to_numeric(df.Quantity.str.replace('Â','').str.strip())
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2022-01-26
    • 1970-01-01
    • 2020-08-17
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多