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

如何在DataFrame中值为shop的行下方插入指定新行?

在指定行下方插入新行的解决方案

可以通过以下步骤用Pandas实现需求:

  1. 定位目标行的索引:找到variable列值为'shop'的行的位置
  2. 构造新行数据:创建包含指定值的Series
  3. 拆分并拼接DataFrame:将原DataFrame拆分为目标行前、目标行、新行、目标行后四部分,重新拼接
  4. 重置索引:避免拼接后出现重复索引

完整代码示例

import pandas as pd

# 构造用户提供的DataFrame(行索引为1-based)
df1 = pd.DataFrame({
    'number': [pd.NA, 3.0, 0.5, pd.NA, 1.0],
    'variable': ['bank', 'shop', 'market', 'government', 'hotel'],
    'values': [True, False, True, True, 'true']
}, index=[1,2,3,4,5])

# 找到shop行的索引
target_idx = df1[df1['variable'] == 'shop'].index[0]

# 构造要插入的新行
new_row = pd.Series({
    'number': 0.2,
    'variable': 'park',
    'values': False
})

# 拆分并拼接DataFrame
df_updated = pd.concat([
    df1.iloc[:target_idx],
    new_row.to_frame().T,
    df1.iloc[target_idx:]
])

# 重置索引(可选,按需保留原索引)
df_updated = df_updated.reset_index(drop=True)

print(df_updated)

执行结果

number    variable values
0     NaN        bank   True
1     3.0        shop  False
2     0.2        park  False
3     0.5      market   True
4     NaN  government   True
5     1.0       hotel   true

如果你的DataFrame是默认0-based索引(行号从0开始),只需调整target_idx的计算和拼接逻辑即可,核心思路完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:42:02