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

如何将不同形状的Pandas DataFrame插入到另一DataFrame指定位置

替换Pandas DataFrame指定列的指定行数据

原始数据

df结构与数据:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A":["A","B","C","D"],
                   "B":[1,np.nan,np.nan,4],
                   "C":[1,456,5464,4],
                   "D":[1,234,9876,4],
                   "E":[1,2,3,4],
                   "F":[1,2,3,4],
                   "G":[1,2,3,4],
                   "H":[1,2,3,4]
                  })

df为4行8列,其中B列第2、3行(索引1、2)为缺失值,C、D列对应行有原始数值。

df2结构与数据:

df2 = pd.DataFrame({'col1':[9,10],
                   'col2':[11,12],
                   'col3':[13,14]})

df2为2行3列,包含待替换的目标数值。

需求说明

将df2的内容插入到df中,替换df里B、C、D列的第2、3行(索引1、2)数据,最终得到如下目标DataFrame:

pd.DataFrame({"A":["A","B","C","D"],
               "B":[1,9,10,4],
               "C":[1,11,12,4],
               "D":[1,13,14,4],
               "E":[1,2,3,4],
               "F":[1,2,3,4],
               "G":[1,2,3,4],
               "H":[1,2,3,4]
              })

解决方案

通过行索引定位+转置赋值完成替换,代码如下:

# 替换指定行和列的数据
df.loc[1:2, ['B', 'C', 'D']] = df2.values.T

# 输出结果
print(df)

说明

  • df.loc[1:2, ['B', 'C', 'D']] 精准定位df中需要替换的行(索引1、2)和列(B、C、D)
  • df2.values.T 将df2的行转置为列,匹配df待替换区域的结构,直接完成赋值替换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:35:00