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

如何将两个DataFrame合并为指定格式?求技术实现方案

实现方法:分步合并展示两个DataFrame

我来帮你搞定这个需求,用Pandas就能轻松实现你想要的展示格式,下面是具体步骤和代码示例:

1. 先构造示例DataFrame

首先根据你给出的数据创建两个目标DataFrame:

import pandas as pd

# 创建DataFrame1
df1 = pd.DataFrame({
    'Col1': ['zbo', 'zbo', 'zbo'],
    'Col2': [123, 6547, 6589],
    'Col': [40, 50, 60]
})

# 创建DataFrame2
df2 = pd.DataFrame({
    'Column': ['tile zbo', 'file abc', 'date 01/09/2018']
})

2. 处理DataFrame2的键值对展示

DataFrame2的每行是key value格式,我们可以分割后转换成key : value的形式输出,这里用split(' ', 1)只分割一次,能避免值里包含空格时出错:

# 遍历DataFrame2的每行,分割并打印键值对
for line in df2['Column']:
    key, value = line.split(' ', 1)
    print(f"{key} : {value}")

3. 展示DataFrame1的完整表格

接着打印DataFrame1,用to_string(index=False)可以去掉默认的索引列,让表格展示更干净:

# 打印分隔线区分两部分内容
print("\n" + "-"*30 + "\n")
# 打印无索引的DataFrame1
print(df1.to_string(index=False))

完整代码&输出效果

把上面的代码整合起来,运行后就能得到你预期的输出:

import pandas as pd

# 创建DataFrame1
df1 = pd.DataFrame({
    'Col1': ['zbo', 'zbo', 'zbo'],
    'Col2': [123, 6547, 6589],
    'Col': [40, 50, 60]
})

# 创建DataFrame2
df2 = pd.DataFrame({
    'Column': ['tile zbo', 'file abc', 'date 01/09/2018']
})

# 处理并打印DataFrame2的键值对
for line in df2['Column']:
    key, value = line.split(' ', 1)
    print(f"{key} : {value}")

# 打印分隔线和DataFrame1
print("\n" + "-"*30 + "\n")
print(df1.to_string(index=False))

运行后输出:

tile : zbo
file : abc
date : 01/09/2018

------------------------------

Col1  Col2  Col
 zbo   123   40
 zbo  6547   50
 zbo  6589   60

可选:保存输出到文件

如果需要把结果保存到本地文件,可以把内容拼接成字符串后写入:

# 拼接输出内容
output_content = ""
for line in df2['Column']:
    key, value = line.split(' ', 1)
    output_content += f"{key} : {value}\n"

output_content += "\n" + "-"*30 + "\n"
output_content += df1.to_string(index=False)

# 写入文件
with open('combined_output.txt', 'w') as f:
    f.write(output_content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:40:49