Pandas中Amount类列转float失败及分组求和异常问题求助
问题解决:无法将带千位分隔符的字符串转为float类型
错误原因
报错could not convert string to float: '10,084.80'的核心原因是数值字符串中包含千位分隔符逗号,Python内置的float()函数无法识别这种格式,直接转换会失败。
解决方案
方法1:读取CSV时直接处理千位分隔符
在pd.read_csv()中使用thousands=','参数,让Pandas自动识别千位分隔符,直接将对应列解析为数值类型:
import pandas as pd from datetime import datetime # 读取时指定千位分隔符,自动解析数值列 df = pd.read_csv(r'C:\Users\Desktop\CustomerData.csv', thousands=',') # 日期清洗逻辑不变 parsed = pd.to_datetime(df["Date"], errors="coerce").fillna(pd.to_datetime(df["Date"],format="%Y-%d-%m",errors="coerce")) ordinal = pd.to_numeric(df["Date"], errors="coerce").apply(lambda x: pd.Timestamp("1899-12-30")+pd.Timedelta(x, unit="D")) df["Date"] = parsed.fillna(ordinal) # 筛选目标数据 newdf = df.loc[(df.Type == "Sales Invoice")] # 列已为数值类型,直接分组求和 df2 = newdf.groupby(['Date','Customer','Type'])["Amount currency", "Amount"].sum()
方法2:读取后手动清洗数值列
如果无法在读取阶段处理,可读取后替换逗号并转换类型:
import pandas as pd from datetime import datetime df = pd.read_csv(r'C:\Users\Desktop\CustomerData.csv') # 日期清洗逻辑不变 parsed = pd.to_datetime(df["Date"], errors="coerce").fillna(pd.to_datetime(df["Date"],format="%Y-%d-%m",errors="coerce")) ordinal = pd.to_numeric(df["Date"], errors="coerce").apply(lambda x: pd.Timestamp("1899-12-30")+pd.Timedelta(x, unit="D")) df["Date"] = parsed.fillna(ordinal) # 清洗数值列:替换逗号为空白,转为float类型 numeric_cols = ["Amount currency", "Amount"] df[numeric_cols] = df[numeric_cols].replace(',', '', regex=True).astype(float) # 筛选目标数据并分组求和 newdf = df.loc[(df.Type == "Sales Invoice")] df2 = newdf.groupby(['Date','Customer','Type'])[numeric_cols].sum()
额外优化建议
- 避免在
groupby().apply()中转换类型,这种方式效率低且易出错,建议先统一转换列类型再执行聚合操作。 - 若需将Date列转为YYYY-MM格式,可在日期处理完成后添加:
df["Date"] = df["Date"].dt.to_period('M'),分组时会自动按年月聚合。
内容的提问来源于stack exchange,提问作者Brian Michaels
相关产品推荐
相关产品推荐

