如何按指定Schema转换DataFrame:补缺失列并删冗余列
调整DataFrame至指定列集合
目标列集合
columns=['index', 'count_1','count_2', 'count_3', 'count_4', 'count_5']
调整规则
- 若输入DataFrame缺少目标列中的某一列,自动添加该列并将所有值设为0
- 若输入DataFrame包含目标列以外的列,直接删除这些多余列
实现代码
import pandas as pd def align_dataframe(df, target_columns): # 重新索引至目标列,缺失列填充0,多余列自动丢弃 return df.reindex(columns=target_columns, fill_value=0)
示例验证
示例1:输入已符合要求
输入DataFrame:
index count_1 count_2 count_3 count_4 count_5 0 1 10 12 45 0 23
输出与输入完全一致,无需调整。
示例2:输入缺少指定列
输入DataFrame:
index count_1 count_3 count_4 count_5 0 1 10 45 0 23
处理后输出:
index count_1 count_2 count_3 count_4 count_5 0 1 10 0 45 0 23
示例3:输入包含多余列
输入DataFrame:
index count_1 count_2 count_3 count_4 count_5 count_6 0 1 10 0 45 0 23 11
处理后输出:
index count_1 count_2 count_3 count_4 count_5 0 1 10 0 45 0 23
内容的提问来源于stack exchange,提问作者math_guy_shy
相关产品推荐
相关产品推荐

