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

如何将3个pandas DataFrame沿对角线拼接为其余值为空的更大DataFrame

实现方案

你可以通过偏移量动态赋值的方式实现,该方案支持任意数量、任意尺寸的小DataFrame对角拼接,无需硬编码位置:

完整实现代码

import pandas as pd
import numpy as np

# 示例小DataFrame
df_gr1 = pd.DataFrame(data=[[5, 4, 7], [1, 9, 6], [2, 8, 3]])
df_gr2 = pd.DataFrame(data=[[3, 2, 7], [5, 1, 8], [4, 9, 6]])
df_gr3 = pd.DataFrame(data=[[2, 3, 9], [8, 5, 6], [7, 1, 4]])

def diagonal_concat(df_list):
    # 计算大表总行列数
    total_rows = sum(df.shape[0] for df in df_list)
    total_cols = sum(df.shape[1] for df in df_list)
    # 初始化全空大表
    res_df = pd.DataFrame(np.full((total_rows, total_cols), np.nan))
    # 记录当前小表的起始行列偏移量
    row_offset, col_offset = 0, 0
    for df in df_list:
        h, w = df.shape
        # 给大表对应区域赋值
        res_df.iloc[row_offset:row_offset+h, col_offset:col_offset+w] = df.values
        # 更新偏移量,准备放下一个小表
        row_offset += h
        col_offset += w
    # 可选:将NaN替换为空字符串,符合空单元格视觉效果
    res_df = res_df.fillna('')
    return res_df

# 调用函数,传入要拼接的DataFrame列表即可
final_df = diagonal_concat([df_gr1, df_gr2, df_gr3])

效果说明

运行后得到的final_df就是目标结构:前3行前3列为df_gr1内容,中间3行中间3列为df_gr2内容,最后3行最后3列为df_gr3内容,其余位置均为空。后续需要填充空单元格时直接对final_df对应位置赋值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:30:01