You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将DataFrame df1的表头设置为DataFrame df2的表头?

Answer

Yes, this operation is absolutely feasible! Depending on whether you want to display this header alongside your data or integrate it into the DataFrame's structure, here are the exact steps to achieve your desired output:

First, let's define the DataFrames as per your example using pandas:

import pandas as pd

# df1: Single-column DataFrame with your specified header string as the column name
df1 = pd.DataFrame(
    [0, 0.75, 1.10, 1.52, 1.59],
    columns=["Speed 1.0 0 201205291004 11.230000000 -97.210000000 -1 Art"]
)

# df2: Two-column DataFrame with your sample data
df2 = pd.DataFrame(
    [[33.55, 45], [61.37, 62], [71.52, 78]]
)

Option 1: Get the exact printed output you want

If you want to print df2 with the header line above the data (matching your desired result exactly), use this code:

# Print the custom header line
print(f"df2 ( {df1.columns[0]} )")
# Print df2 without its default column headers
print(df2.to_string(header=False))

This will output:

df2 ( Speed 1.0 0 201205291004 11.230000000 -97.210000000 -1 Art )
0 33.55 45
1 61.37 62
2 71.52 78

Option 2: Assign the header string to df2's columns

If you want df2's columns to formally use that header string (even though there are two columns), you can set both column names to the same value:

df2.columns = [df1.columns[0]] * 2

Now when you print df2, it will show your custom string as the name for both data columns.

Option 3: Save the formatted output to a file

If you need to export this structure to a text or CSV file, use this approach:

# Write the header line to the file first
with open("df2_output.txt", "w") as file:
    file.write(f"df2 ( {df1.columns[0]} )\n")
# Append df2's data without default headers
df2.to_csv("df2_output.txt", mode="a", header=False, sep=" ")

This will create a file with your desired structure.

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

火山引擎 最新活动