Python DataFrame将键值对转为标准表格:transpose无效求解决方法
问题:将键值对格式的DataFrame转换为标准表格
我有一组键值对格式的Python DataFrame数据,每行包含字段名(如Year、Month、Filed Date)与对应值,每3行构成一条完整记录。尝试使用transpose函数将其转换为以字段名为列标题的标准表格,但结果未达预期。请问应使用何种函数实现如下转换效果?
原数据
Year 2020 Month SEPTEMBER Filed Date 29-11-2020 Year 2022 Month JULY Filed Date 20-08-2022 Year 2022 Month APRIL Filed Date 20-05-2022 Year 2017 Month AUGUST Filed Date 21-09-2017 Year 2018 Month JULY Filed Date 03-02-2019 Year 2021 Month MAY Filed Date 22-06-2021 Year 2017 Month DECEMBER Filed Date 19-01-2018 Year 2018 Month MAY Filed Date 03-02-2019 Year 2019 Month MARCH Filed Date 28-09-2019
目标效果
Year Month Filed Date 2020 September 29-11-2020 2022 July 20-08-2022 ...
解决方案
transpose函数仅能单纯行转列,无法处理这种按固定行数分组的键值对结构。你可以通过分组+重塑的方式实现目标,以下是两种实用方法:
方法1:使用pivot函数(推荐)
假设你的DataFrame列名为['Field', 'Value'](第一列是字段名,第二列是对应值),步骤如下:
- 生成分组ID:每3行对应一条完整记录,用
df.index // 3给每行分配分组标签 - 用
pivot将字段名转为列,值对应到分组中 - 可选:将Month列格式调整为首字母大写(匹配目标效果)
示例代码:
import pandas as pd # 模拟原DataFrame data = [ ['Year', 2020], ['Month', 'SEPTEMBER'], ['Filed Date', '29-11-2020'], ['Year', 2022], ['Month', 'JULY'], ['Filed Date', '20-08-2022'], ['Year', 2022], ['Month', 'APRIL'], ['Filed Date', '20-05-2022'], # 其他数据行... ] df = pd.DataFrame(data, columns=['Field', 'Value']) # 生成分组ID df['Group'] = df.index // 3 # 重塑表格 result = df.pivot(index='Group', columns='Field', values='Value').reset_index(drop=True) # 调整Month列格式(可选) result['Month'] = result['Month'].str.title() print(result)
方法2:使用groupby函数
通过groupby按分组ID聚合,将每组的键值对转为一行记录:
result = df.groupby(df.index // 3).apply( lambda x: pd.Series(x['Value'].values, index=x['Field'].values) ).reset_index(drop=True) # 同样可选调整Month格式 result['Month'] = result['Month'].str.title()
两种方法最终都会输出目标格式的标准表格,字段名作为列标题,每条完整记录占一行。
内容的提问来源于stack exchange,提问作者Sam Wittwicky
相关产品推荐
相关产品推荐

