如何在Pandas DataFrame中为每个分组添加一行?
为DataFrame中每个Region添加指定固定行
原始DataFrame:
| Region | Descript | Material | Input |
|---|---|---|---|
| UK | Bottle | #1 | 500 |
| UK | Cap | #5 | 20 |
| India | Bottle | #1 | 400 |
| India | Cap | #5 | 2 |
目标DataFrame:
| Region | Descript | Material | Input |
|---|---|---|---|
| UK | Bottle | #1 | 500 |
| UK | Cap | #5 | 20 |
| UK | other | #7 | NA |
| India | Bottle | #1 | 400 |
| India | Cap | #5 | 2 |
| India | other | #7 | NA |
需求是给每个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
相关产品推荐
相关产品推荐

