pandas DataFrame新增列并追加指定值行其余位置填零的实现方法
pandas实现新增列并追加指定值行的方案
完整实现代码
你可以直接替换代码中原始DataFrame、新列名、新值三个参数适配自己的场景:
import pandas as pd # 原始DataFrame,可替换为你自己已有的DataFrame df = pd.DataFrame({ 'A': [1,4], 'B': [2,5], 'C': [3,6] }) # 自定义输入参数:新列名、对应指定值 new_col_name = 'D' new_col_value = 7 # 第一步:添加新列,已有行的新列值统一填充0 df[new_col_name] = 0 # 第二步:构造待追加的新行,仅新列为指定值,其余列全填0 new_row = pd.Series({col: new_col_value if col == new_col_name else 0 for col in df.columns}) # 追加新行到DataFrame末尾,自动重置行索引 df = pd.concat([df, new_row.to_frame().T], ignore_index=True) # 打印结果验证 print(df)
输出结果
运行后得到的效果和示例完全一致:
A B C D 0 1 2 3 0 1 4 5 6 0 2 0 0 0 7
补充说明
- 如果你使用pandas 1.4及以下旧版本,也可以用更简洁的
append写法实现行追加:df = df.append(new_row, ignore_index=True),更高版本建议使用pd.concat保证兼容性 - 若需要保留原始行索引,删除
ignore_index=True参数即可
内容的提问来源于stack exchange,提问作者VARUN ISAC
相关产品推荐
相关产品推荐

