Pandas按order_type条件为DataFrame新增traded_value列的实现方法
新增traded_value列的实现方案
首先梳理现有代码可直接修正的问题:
- 执行完列删除操作后,重复调用了无参数的
orders=pd.read_csv(),这行代码会直接清空前面的列筛选结果,还会因传入空路径触发读取报错,需直接删除该行 - 原有条件判断中使用的全大写
MARKET/LIMIT取值,需要和实际DataFrame内的字符串格式对齐,避免大小写不匹配导致规则完全不生效
可直接复用的代码实现
方案1:适配现有np.select的编码风格
# 统一order_type字段的字符串大小写,消除判断偏差 orders['order_type'] = orders['order_type'].str.upper() # 定义匹配条件和对应计算逻辑 trade_conditions = [ orders['order_type'] == 'MARKET', orders['order_type'] == 'LIMIT' ] trade_results = [ orders['average_price'] * orders['quantity'], orders['price'] * orders['quantity'] ] orders['traded_value'] = np.select(trade_conditions, trade_results)
方案2:使用loc分步赋值,大数据量下运行效率更高
# 统一order_type字段的字符串格式 orders['order_type'] = orders['order_type'].str.upper() # 按订单类型分别计算成交金额 orders.loc[orders['order_type'] == 'MARKET', 'traded_value'] = orders['average_price'] * orders['quantity'] orders.loc[orders['order_type'] == 'LIMIT', 'traded_value'] = orders['price'] * orders['quantity']
注意:实现前要确认
quantity、average_price、price三个字段为数值类型,若为字符串格式需要先做类型转换,否则乘法计算会触发类型错误。
内容的提问来源于stack exchange,提问作者Huzefa Sadikot
相关产品推荐
相关产品推荐

