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

如何在Pandas DataFrame中为每个分组添加一行?

为DataFrame中每个Region添加指定固定行

原始DataFrame:

RegionDescriptMaterialInput
UKBottle#1500
UKCap#520
IndiaBottle#1400
IndiaCap#52

目标DataFrame:

RegionDescriptMaterialInput
UKBottle#1500
UKCap#520
UKother#7NA
IndiaBottle#1400
IndiaCap#52
Indiaother#7NA

需求是给每个Region追加一行固定内容的记录:Descript为"other",Material为"#7",Input为空值。以下是适合新手的简单实现方案:

import pandas as pd

# 构建原始DataFrame
df = pd.DataFrame({
    "Region": ["UK", "UK", "India", "India"],
    "Descript": ["Bottle", "Cap", "Bottle", "Cap"],
    "Material": ["#1", "#5", "#1", "#5"],
    "Input": [500, 20, 400, 2]
})

# 1. 获取所有不重复的Region值
unique_regions = df["Region"].unique()

# 2. 批量生成要添加的固定行数据
new_rows = pd.DataFrame({
    "Region": unique_regions,
    "Descript": "other",
    "Material": "#7",
    "Input": pd.NA
})

# 3. 合并原始数据与新行,并重设索引
df2 = pd.concat([df, new_rows], ignore_index=True)

# 可选:按Region排序,让同一地区的记录集中展示
df2 = df2.sort_values("Region", ignore_index=True)

print(df2)

核心逻辑是先提取所有唯一地区,批量生成对应固定行,再合并到原数据中,运行后就能得到目标结构的DataFrame。

内容的提问来源于stack exchange,提问作者John Luke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:20:22