You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用两个DataFrame计算房地产门户CPE?解决报错及0数据缺失

房地产门户CPE计算问题修复:补全0查询量门户+解决类型错误

问题核心

你遇到两个关键问题:

  1. 合并结果缺失查询量为0的门户:使用inner连接仅保留两边都存在的数据,无查询的门户未被统计,因此被过滤
  2. CPE计算报错TypeError: unsupported operand type(s) for /: 'str' and 'int':CostQ124列是字符串类型,无法与整数类型的Enquiries执行除法运算

分步修复+简洁实现

1. 正确统计含0查询量的门户数据

基于成本表的所有门户做匹配,确保无查询的门户显示0:

# 筛选Portal类查询数据
portal_enquiries = enquiries_q1_2024[enquiries_q1_2024['Sub-origin'] == 'Portal']

# 按Origin统计查询量,转成DataFrame
enquiry_counts = portal_enquiries.groupby('Origin').size().reset_index(name='Enquiries')

# 补全成本表中所有门户,无查询的设为0
all_portals = portal_costs['Origin'].unique()
enquiry_counts = enquiry_counts.set_index('Origin').reindex(all_portals, fill_value=0).reset_index()

2. 转换成本列为数值类型

将字符串类型的成本值转为数值型,避免类型错误:

portal_costs['CostQ124'] = pd.to_numeric(portal_costs['CostQ124'], errors='coerce')

3. 合并数据并计算CPE

用left连接确保所有门户被保留,同时处理查询量为0的情况(避免除以0报错):

# 合并查询量与成本数据
cost_per_enquire = pd.merge(enquiry_counts, portal_costs, on='Origin', how='left')

# 计算CPE,查询量为0时设为NaN(可根据需求调整为其他值)
cost_per_enquire['CPE'] = cost_per_enquire.apply(
    lambda row: row['CostQ124'] / row['Enquiries'] if row['Enquiries'] != 0 else pd.NA,
    axis=1
)

完整简洁版本

整合步骤,减少冗余代码:

# 1. 筛选+统计查询量,补全0查询门户
portal_enquiries = enquiries_q1_2024[enquiries_q1_2024['Sub-origin'] == 'Portal']
enquiry_counts = portal_enquiries.groupby('Origin').size().reindex(portal_costs['Origin'], fill_value=0).reset_index(name='Enquiries')

# 2. 转换成本列类型+合并数据
portal_costs['CostQ124'] = pd.to_numeric(portal_costs['CostQ124'], errors='coerce')
cost_per_enquire = pd.merge(enquiry_counts, portal_costs, on='Origin', how='left')

# 3. 计算CPE(自动处理0值情况)
cost_per_enquire['CPE'] = cost_per_enquire['CostQ124'].div(cost_per_enquire['Enquiries']).where(cost_per_enquire['Enquiries'] != 0)

最终结果说明

最终的cost_per_enquire会包含你需要的四列:Origin(所有门户)、Enquiries(含0值)、CostQ124(数值型)、CPE(正常计算结果或NaN)。

内容的提问来源于stack exchange,提问作者Rafael Fontes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:45:57