【问题标题】:pandas convert object to type that able to do calculationpandas 将对象转换为能够进行计算的类型
【发布时间】:2018-04-14 12:45:59
【问题描述】:

我有一个 df 列数据类型是一个对象,例如 value = $45.00 我尝试总结该列中的总金额,但出现以下错误:

输出:

Wash_amount = df['WASHING'].sum()

TypeError: unsupported operand type(s) for +: 'int' and 'str'

在此之前,我尝试将所有列转换为数字:

df = df.apply(pd.to_numeric, errors='coerce')

但是所有的值都变成了“nan”,这不是我想要的。

那么如何转换列值类型,我可以求和。

或者,如果数据中包含“$”,我如何检查所有列,以将所有列转换为浮点数而不是逐列转换?

谢谢

【问题讨论】:

    标签: pandas type-conversion


    【解决方案1】:

    在应用任何转换之前,您需要从字符串值中删除 $ 前缀。我采用了以下名为“sample.csv”的示例数据文件

    date,Washing
    12/01/1927,$251.66
    01/01/1928,$250.37
    02/01/1928,$248.84
    03/01/1928,$277.96
    04/01/1928,$284.74
    05/01/1928,$286.66
    06/01/1928,$275.94
    07/01/1928,$280.12
    08/01/1928,$300.88
    09/01/1928,$301.25
    10/01/1928,$310.74
    11/01/1928,$348.01
    12/01/1928,$351.05
    01/01/1929,$371.09
    02/01/1929,$368.93
    

    然后是下面的代码

    import pandas as pd
    df = pd.DataFrame(pd.read_csv("sample.csv"))
    
    df['Washing'] = df['Washing'].map(lambda x: x.lstrip('$'))
    print(df.head())
    df.Washing = df.Washing.astype('float')
    print(df.dtypes)
    Wash_amount = df['Washing'].sum()
    print(Wash_amount)
    

    【讨论】:

    • df['Washing'] = df['Washing'].map(lambda x: x.lstrip('$')) 给出这个错误:AttributeError: 'float' object has no attribute' lstrip'
    • lstrip 将应用于 dtype: object。因此,请先在列上应用 lstrip,然后再将其转换为“float”。请按照给出的示例代码中的步骤顺序进行
    • 嗨,是的,我一步一步来?
    • 列是对象类型
    • 请检查值是否包含除数字以外的任何其他字符。如果它包含任何其他字母/特殊字符,它将不起作用
    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2023-03-09
    • 2018-11-27
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多