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

如何转置表格并保留列标题?Pandas DataFrame处理方案

问题描述

现有一个尺寸为(31,2)的Pandas DataFrame,结构如下:

DecemberJanuary
11
22
......
3131

可通过以下代码构建该DataFrame:

import pandas as pd

numbers = []
for i in range(1, 32):
    numbers.append(i)

df = pd.DataFrame({
    'December': numbers,
    'January': numbers
})

需要将其转换为如下形式的表格(每行包含对应列的所有数值):

DecemberJanuary
1 2 3 ... 311 2 3 ... 31
解决方法

可以通过agg或apply方法将每列的所有数值拼接为字符串,再转换为单行的DataFrame,具体代码如下:

方法一:使用agg函数

# 对每列执行拼接操作,转成单行DataFrame
df_result = df.agg(lambda x: ' '.join(map(str, x))).to_frame().T

方法二:使用apply函数

# 遍历每列,将数值转为字符串后拼接,再转成单行DataFrame
df_result = df.apply(lambda col: ' '.join(col.astype(str)), axis=0).to_frame().T

执行上述代码后,df_result即为目标格式的DataFrame,尺寸为(1,2),每个单元格包含对应月份的所有日期数值(以空格分隔)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:17:26