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

如何按交替行规则行向合并两个Pandas DataFrame?

Hey there! Let's figure out how to interleave two Pandas DataFrames row-wise exactly as you described—A's first row, then B's first, A's second, B's second, and so on.

First, let's start with some sample data to make this concrete:

import pandas as pd

# Example DataFrames with 3 rows each
df_a = pd.DataFrame({'Value': [10, 20, 30], 'Label': ['X', 'Y', 'Z']})
df_b = pd.DataFrame({'Value': [40, 50, 60], 'Label': ['P', 'Q', 'R']})

Method 1: Add a helper index column (most intuitive for beginners)

This approach uses a helper column to track row positions, then sorts to get the interleaved order:

# Add an index column to both DataFrames
df_a['row_id'] = range(len(df_a))
df_b['row_id'] = range(len(df_b))

# Combine and sort: first by row_id, then prioritize A over B
combined = pd.concat([df_a.assign(source='A'), df_b.assign(source='B')])
result = combined.sort_values(
    by=['row_id', 'source'],
    key=lambda x: x.map({'A': 0, 'B': 1})  # Ensure A comes before B for each row_id
).drop(columns=['row_id', 'source']).reset_index(drop=True)

Method 2: Numpy reshape (fastest for large datasets)

If you're working with big DataFrames, this method leverages numpy's array manipulation for speed:

import numpy as np

# Make sure both DataFrames have the same columns first
assert df_a.columns.equals(df_b.columns), "DataFrames must have identical columns"

# Stack the data column-wise, then reshape to interleave rows
interleaved_data = np.column_stack([df_a.values, df_b.values]).reshape(-1, df_a.shape[1])
result = pd.DataFrame(interleaved_data, columns=df_a.columns)

Method 3: Multi-index concat (concise one-liner)

For a more Pandas-idiomatic one-liner, use multi-index stacking:

result = pd.concat([df_a, df_b], keys=['A', 'B']).unstack(0).stack(1).reset_index(drop=True)

All these methods will give you a 2n-row DataFrame in the exact order you want. Let me know if you need clarification on any of them!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:24:12