Pandas groupby求和丢失数值列,如何保留目标列?
问题描述
以下是一段Python/Pandas代码:
standardized_df = get_somehow() standardized_df['TermDaysAmountProduct'] = standardized_df['TermDays'] * standardized_df['Amount'] standardized_df['DaysToCollectAmountProduct'] = standardized_df['DaysToCollect'] * standardized_df['Amount'] logger.info("standardized_df cols are {}".format(standardized_df.head())) grouped_df = standardized_df.groupby(["Customer ID"], as_index=False).sum() logger.info("grouped_df cols are {}".format(grouped_df.head()))
运行后日志输出:
standardized_df cols are Customer ID Customer Name ... TermDaysAmountProduct DaysToCollectAmountProduct grouped_df cols are Customer ID Amount
执行groupby求和后,原本应为数值类型的TermDaysAmountProduct和DaysToCollectAmountProduct列被意外移除,需要解决如何在求和后保留这两列的问题。
解决方法
核心原因
这两列被排除的大概率原因是数据类型不是数值型(比如object类型),Pandas的sum()方法默认仅对数值型列执行求和操作,非数值列会被自动过滤。
具体解决方案
- 检查并转换列的数据类型
先确认目标列的类型,若为object则转为数值类型:
# 根据实际数据选择int或float类型,errors='coerce'将无效值转为NaN standardized_df['TermDaysAmountProduct'] = pd.to_numeric(standardized_df['TermDaysAmountProduct'], errors='coerce') standardized_df['DaysToCollectAmountProduct'] = pd.to_numeric(standardized_df['DaysToCollectAmountProduct'], errors='coerce')
转换完成后再执行groupby.sum(),两列会被正常求和并保留。
- 显式指定要求和的列
如果想完全控制聚合列,直接指定需要聚合的字段及规则:
grouped_df = standardized_df.groupby(["Customer ID"], as_index=False).agg({ 'Amount': 'sum', 'TermDaysAmountProduct': 'sum', 'DaysToCollectAmountProduct': 'sum' })
这种方式不仅能确保目标列被保留,还能针对不同列设置不同聚合逻辑。
- 排查原始计算列的类型
如果TermDays或DaysToCollect本身是非数值类型,相乘后会导致乘积列变成object。先检查原始参与计算的列:
print(standardized_df[['TermDays', 'DaysToCollect', 'Amount']].dtypes)
确保这些列都是数值型,避免生成的乘积列类型异常。
内容的提问来源于stack exchange,提问作者hotmeatballsoup
相关产品推荐
相关产品推荐

