Pandas全外连接后如何填充空白Product列及PnL列NaN值为0
解决方案
方案1:更简单的从头实现(推荐,无后续补空值逻辑)
不需要用全外连接,先构造「全量产品+全量区域」的笛卡尔积作为基准表,再左关联原表数据即可从根源避免空值问题,一步到位:
import pandas as pd # 1. 定义全量区域列表 all_regions = ['Northeast', 'Southeast', 'Mid-Atlantic', 'Midwest', 'Prairies', 'Southwest', 'Northwest', 'California'] # 2. 提取原df中所有不重复的产品列表 all_products = df['Product'].unique() # 3. 构造笛卡尔积基准表,单日期场景直接统一赋值日期即可 single_date = df['Date'].iloc[0] base_df = pd.MultiIndex.from_product([all_products, all_regions], names=['Product', 'Region']).to_frame(index=False) base_df['Date'] = single_date # 4. 左关联原数据,空PnL直接填0 result = base_df.merge(df, on=['Date', 'Product', 'Region'], how='left').fillna(0)
若你的df包含多个日期数据,只需把日期也加入笛卡尔积维度即可:
all_dates = df['Date'].unique() base_df = pd.MultiIndex.from_product([all_dates, all_products, all_regions], names=['Date', 'Product', 'Region']).to_frame(index=False)
方案2:针对当前已生成的中间表的修复方法
如果你不想重走合并流程,直接填充已有中间表的空Product值也可以:
# 提取所有不重复的产品 all_products = df['Product'].unique() # 筛选出Product为空的行,按Region去重后给每个Region分配所有产品 empty_rows = merged_df[merged_df['Product'].isna()].drop_duplicates(subset=['Region']) filled_empty = empty_rows.drop(columns=['Product']).merge(pd.Series(all_products, name='Product'), how='cross') # 替换原中间表里的空Product行 merged_df = pd.concat([merged_df[merged_df['Product'].notna()], filled_empty], ignore_index=True) # 若新生成行仍有PnL空值再补0 merged_df = merged_df.fillna(0)
内容的提问来源于stack exchange,提问作者Zza
相关产品推荐
相关产品推荐

