Python中基于列分区与条件填充数据行
为Pandas数据框按ID补全缺失B值行并填充C列为0
问题场景
现有数据框包含ID(A列)、B值和对应C值,需要为每个ID补充possible_B_values中缺失的B值行,新行的C列设为0。
原数据:
A B C 0 id1 2 10 1 id1 3 20 2 id2 1 30
possible_B_values = [1,2,3]
期望结果:
A B C 0 id1 1 0 1 id1 2 10 2 id1 3 20 3 id2 1 30 4 id2 2 0 5 id2 3 0
方法一:生成笛卡尔积后左连接
通过生成所有ID与B值的完整组合,再和原数据左连接,最后填充缺失值为0,步骤清晰易懂:
import pandas as pd # 初始化原数据框 df = pd.DataFrame({ 'A': ['id1', 'id1', 'id2'], 'B': [2, 3, 1], 'C': [10, 20, 30] }) possible_B_values = [1, 2, 3] # 获取所有唯一ID unique_ids = df['A'].unique() # 生成ID与B值的完整组合 full_combinations = pd.MultiIndex.from_product( [unique_ids, possible_B_values], names=['A', 'B'] ).to_frame(index=False) # 左连接原数据,填充C列缺失值为0 result_df = pd.merge(full_combinations, df, on=['A', 'B'], how='left') result_df['C'] = result_df['C'].fillna(0).astype(int) print(result_df)
方法二:GroupBy + Reindex
利用分组后重新索引的方式,代码更简洁,适合熟悉Pandas分组操作的场景:
import pandas as pd df = pd.DataFrame({ 'A': ['id1', 'id1', 'id2'], 'B': [2, 3, 1], 'C': [10, 20, 30] }) possible_B_values = [1, 2, 3] # 设置双索引后分组,对每个组的B列重新索引并填充0 result_df = df.set_index(['A', 'B']).groupby('A')['C'].apply( lambda x: x.reindex(possible_B_values, fill_value=0) ).reset_index() print(result_df)
两种方法都能得到符合预期的结果,可根据数据规模和个人习惯选择。
内容的提问来源于stack exchange,提问作者Jacob Saki
相关产品推荐
相关产品推荐

