pandas中按条件将DataFrame内debit行交易值转负时值丢失问题
pandas实现debit类型交易金额转负值的异常排查与解决
需求说明
- 待处理的DataFrame包含
user_id、date、type、transaction_part_sum、transaction_part_count字段 - 规则要求:
type取值为debit的行,当前transaction_part_sum为正值,需转换为对应负数;credit类型行的该字段值保持原有正值不变
原始数据示例
user_id date type transaction_part_sum transaction_part_count 1000616411022604 2011-12-20 debit 51.58 1 1000616411022604 2013-06-10 debit 25.52 1 1000616411022604 2013-11-07 credit 533.29 1 1000616411022604 2013-12-26 debit 3.82 1 1000616411022604 2013-12-31 credit 259.68 1 1000616411022604 2014-01-02 debit 79.10 1 1000616411022604 2014-02-25 debit 9.99 1 1000616411022604 2014-03-26 debit 3.42 1 1000616411022604 2014-04-02 debit 71.90 1
已尝试的方案与异常表现
最初使用的实现代码:
grouped.loc[grouped['type'] == 'debit', 'transaction_part_sum'] = -1 * grouped['transaction_part_sum']
异常现象:
- 代码执行后,所有
debit行的transaction_part_sum字段变为空值 - 若将代码中的
-1替换为任意正数做乘法,对应列可以正常更新数值
执行后的异常输出示例:
output: user_id date type transaction_part_sum transaction_part_count 1000616411022604 2011-12-20 debit 1 1000616411022604 2013-06-10 debit 1 1000616411022604 2013-11-07 credit 533.29 1 1000616411022604 2013-12-31 credit 259.68 1 1000616411022604 2013-12-26 debit 1 1000616411022604 2014-01-02 debit 1 1000616411022604 2014-02-25 debit 1 1000616411022604 2014-03-26 debit 1 1000616411022604 2014-04-02 debit 1
问题根因
原有代码的核心问题是赋值时的索引范围不匹配:pandas执行loc赋值操作时,会强制对赋值号左右两侧的Series做索引对齐。上述代码中,赋值号左侧是筛选出的debit行的子对象,仅包含debit行的索引;但赋值号右侧取了全表的transaction_part_sum列,对应全量行的索引。两者索引范围不一致时,无法匹配的位置会被自动填充为NaN,最终导致debit行的数值全部变为空。
正确实现方案
方案1:对齐筛选范围的loc赋值(最稳妥,推荐)
先固定筛选条件,让赋值号左右两侧的取值范围完全一致,从根源避免索引对齐问题:
# 先定义debit类型的筛选掩码 debit_mask = grouped['type'] == 'debit' # 右侧仅取掩码对应的行的数值,与左侧范围完全匹配 grouped.loc[debit_mask, 'transaction_part_sum'] = -grouped.loc[debit_mask, 'transaction_part_sum']
方案2:用numpy.where整列计算(效率高)
跳过loc的分步赋值,直接对整列做条件判断生成新值,适合大数据量场景:
import numpy as np grouped['transaction_part_sum'] = np.where( grouped['type'] == 'debit', -grouped['transaction_part_sum'], grouped['transaction_part_sum'] )
方案3:逐行apply判断(代码直观,适合小数据量)
逐行遍历判断类型,直接修改对应数值,可读性强但数据量大时效率偏低:
grouped['transaction_part_sum'] = grouped.apply( lambda row: -row['transaction_part_sum'] if row['type'] == 'debit' else row['transaction_part_sum'], axis=1 )
内容的提问来源于stack exchange,提问作者pvr
相关产品推荐
相关产品推荐

