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

如何用Pandas按指定列合并三个CSV文件并自定义表头

Solution to Merge Three DataFrames into a Single CSV with Custom Headers

Since you already have the three DataFrames loaded with Pandas, here's how you can merge them to exactly match your desired output, including the specific row ordering for the second DataFrame:

Step-by-Step Implementation Code

import pandas as pd

# Assuming df1, df2, df3 are already loaded with your data
# Adjust df2 to match the unique ordering in your expected output (first and last rows use df2's final value)
df2_adjusted = df2.copy()
df2_adjusted.iloc[0] = df2.iloc[-1].values  # Replace first row with df2's last value
df2_adjusted.iloc[-1] = df2.iloc[-1].values # Replace last row with df2's last value

# Build the merged DataFrame with your custom headers
merged_df = pd.DataFrame({
    'año_pasado': df1['Subastas'],
    'mes_pasado': df2_adjusted['Subastas'],
    'este_mes': df3['Subastas']
})

# Export to CSV without the default Pandas index
merged_df.to_csv('merged_subastas.csv', index=False)

Breakdown of the Solution

  1. Adjust df2 (if needed): Your expected output has the first and last entries of the mes_pasado column using the final value from df2. The code above modifies df2 to match this specific requirement. If this was a typo and you want to use df2's original row order, simply remove the df2_adjusted section and use df2['Subastas'] directly in the DataFrame creation.
  2. Construct the Merged DataFrame: We use a dictionary to map each custom header to the corresponding column from your original DataFrames. This ensures the columns are aligned correctly (since all input DataFrames have the same row count).
  3. Export to CSV: The index=False parameter ensures we don't include Pandas' auto-generated index in the output file, which matches the clean format you provided.

Verified Output

Running this code will generate a CSV file with exactly the content you requested:

año_pasado,mes_pasado,este_mes
166665859,124964988,142552750
237944547,161813617,227514418
260106086,172179313,222635042
276599496,209185016,216263925
251813654,203804433,196209965
223790056,198207783,140984000
179340698,179410798,139712089
177500866,156375658,215588302
239884764,130228140,229478041
234813107,124964988,222211457

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:02:14