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

如何将单行DataFrame与多行DataFrame按需求合并?

解决方法

你可以用以下几种Pandas方法实现需求:

方法一:重复行后替换列

这是最直接的方式,先把df1的单行重复到和df2行数一致,再用df2的Price和Qty替换原有列:

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({'Col1': ['A'], 'Col2': ['B'], 'Price': [16], 'Qty': [5]})
df2 = pd.DataFrame({'Price': [8, 16, 6], 'Qty': [2.5, 5, 1.5]})

# 重复df1的行,次数等于df2的行数
result = pd.concat([df1]*len(df2), ignore_index=True)
# 替换Price和Qty列
result[['Price', 'Qty']] = df2[['Price', 'Qty']]

print(result)

输出结果:

Col1 Col2  Price  Qty
0    A    B      8  2.5
1    A    B     16  5.0
2    A    B      6  1.5

方法二:交叉连接(通用场景)

如果后续df1可能有多行,交叉连接的方式更通用,通过临时键生成所有组合后替换列:

import pandas as pd

df1 = pd.DataFrame({'Col1': ['A'], 'Col2': ['B'], 'Price': [16], 'Qty': [5]})
df2 = pd.DataFrame({'Price': [8, 16, 6], 'Qty': [2.5, 5, 1.5]})

# 添加临时键用于交叉连接
df1['tmp_key'] = 1
df2['tmp_key'] = 1

# 合并后清理列
result = pd.merge(df1, df2, on='tmp_key')
result = result.drop(columns=['Price_x', 'Qty_x', 'tmp_key']).rename(columns={'Price_y': 'Price', 'Qty_y': 'Qty'})

print(result)

方法三:简洁的链式写法

用repeat生成重复行,再通过assign直接覆盖列,代码最简洁:

import pandas as pd

df1 = pd.DataFrame({'Col1': ['A'], 'Col2': ['B'], 'Price': [16], 'Qty': [5]})
df2 = pd.DataFrame({'Price': [8, 16, 6], 'Qty': [2.5, 5, 1.5]})

result = df1.loc[df1.index.repeat(len(df2))].reset_index(drop=True).assign(**df2)

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:50:57